
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
C++ code to count number of lucky numbers with k digits
Suppose we have an array A with n elements, and also another number x. We know the lucky numbers are are positive numbers whose decimal representation only contains lucky digits 4 and 7. Form the given n positive integers. We have to count how many of those have not more than k lucky digits?
So, if the input is like A = [44, 74, 474, 154]; k = 2, then the output will be 3, because there are three lucky numbers 44, 74 and 474 but 474 has three lucky digits which is more than k. Also 154 has one lucky digit which is acceptable.
Steps
To solve this, we will follow these steps −
n := size of A f := 0 for initialize i := 0, when i < n, update (increase i by 1), do: c := 0 while A[i] is not equal to 0, do: if A[i] mod 10 is same as 4 or A[i] mod 10 is same as 7, then: (increase c by 1) A[i] := A[i] / 10 if c <= k, then: (increase f by 1) return f
Example
Let us see the following implementation to get better understanding −
#include<bits/stdc++.h> using namespace std; int solve(vector<int> A, int k){ int n = A.size(); int f = 0; for (int i = 0; i < n; ++i){ int c = 0; while (A[i] != 0){ if (A[i] % 10 == 4 || A[i] % 10 == 7) c++; A[i] /= 10; } if (c <= k) f++; } return f; } int main(){ vector<int> A = {44, 74, 474, 154}; int k = 2; cout << solve(A, k) << endl; }
Input
{44, 74, 474, 154}, 2
Output
3
- Related Articles
- C++ code to find total number of digits in special numbers
- Program to count number of stepping numbers of n digits in python
- Count Numbers with Unique Digits in C++
- Lucky Numbers
- Count of Numbers in Range where the number does not contain more than K non zero digits in C++
- Count Numbers with N digits which consists of even number of 0's in C++
- Count Numbers with N digits which consists of odd number of 0's in C++
- Fetch Numbers with Even Number of Digits JavaScript
- Find Numbers with Even Number of Digits in Python
- Total number of non-decreasing numbers with n digits
- C++ Program to check if a given number is Lucky (all digits are different)
- How to count digits of given number? JavaScript
- C++ code to count copy operations without exceeding k
- C++ code to count number of unread chapters
- Count numbers with same first and last digits in C++

Advertisements