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

Updated on: 15-Mar-2022

736 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements