# Numbers At Most N Given Digit Set in C++

Suppose we have one sorted set of digits D, a non-empty subset of {'1', '2', '3', '4', '5', '6', '7', '8', '9'} except 0. Now, we will write some numbers using these digits, using each digit as many times as we want. So, if D = {'2','3','7'}, we may write numbers such as '23', '771', '2372327'.

Now we have to find the number of positive integers that can be written that are less than or equal to N.

So, if the input is like D = [2,3,4,7], N = 100, then the output will be 20, as the numbers can be 2, 3, 4, 7, 22, 23, 24, 27, 32, 33, 34, 37, 42, 43, 44, 47, 72, 73, 74, 77. All other numbers are greater than 100.

To solve this, we will follow these steps −

• n := convert N to string

• sz := size of n, ret := 0

• for initialize i := 1, when i < sz, update (increase i by 1), do −

• ret := ret + (size of D)^i

• for initialize i := 0, when i < sz, update (increase i by 1), do −

• for each string x in D −

• if x[0] < n[i], then −

• ret := ret + (size of D)^(sz - i - 1)

• otherwise when x[0] is same as n[i], then −

• if not hasSameNum is non-zero, then −

• return ret

• return ret + 1

Let us see the following implementation to get better understanding −

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int atMostNGivenDigitSet(vector<string> &D, int N) {
string n = to_string(N);
int sz = n.size();
int ret = 0;
for (int i = 1; i < sz; i++) {
ret += pow(D.size(), i);
}
for (int i = 0; i < sz; i++) {
for (string &x : D) {
if (x[0] < n[i]) {
ret += pow(D.size(), sz - i - 1);
} else if (x[0] == n[i]) {
}
}
return ret;
}
return ret + 1;
}
};
main(){
Solution ob;
vector<string> v = {"2","3","4","7",};
cout << (ob.atMostNGivenDigitSet(v, 100));
}

## Input

{"2","3","4","7"}, 100

## Output

20