Numbers With Repeated Digits in C++

C++Server Side ProgrammingProgramming

Suppose we have a positive integer N, we have to find the number of positive integers less than or equal to N that have at least 1 repeated digit .

So, if the input is like 99, then the output will be 9, as we have numbers like 11, 22, 33, 44, 55, 66, 77, 88, 99.

To solve this, we will follow these steps −

  • Define a function A(), this will take m, n,

    • ret := 1

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

      • ret := ret * m

      • (decrease m by 1)

    • return ret

  • From the main method do the following −

  • Define an array arr

  • for initialize i := N + 1, when i > 0, update i := i / 10, do −

    • insert first element of arr at index i mod 10 into arr

  • ret := 0

  • n := size of arr

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

    • ret := ret + 9 * A(9, i - 1)

  • Define one set visited

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

    • digit := arr[i]

    • for initialize j := (if i is same as 0, then 1, otherwise 0), when j < digit, update (increase j by 1), do −

      • if j is in visited, then −

        • Ignore following part, skip to the next iteration

      • ret := ret + A(9 - i, n - i - 1)

    • if digit is in visited, then −

      • Come out from the loop

    • insert digit into visited

  • return N - ret

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int A(int m, int n){
      int ret = 1;
      for (int i = 0; i < n; i++) {
         ret *= m;
         m--;
      }
      return ret;
   }
   int numDupDigitsAtMostN(int N){
      vector<int> arr;
      for (int i = N + 1; i > 0; i /= 10) {
         arr.insert(arr.begin(), i % 10);
      }
      int ret = 0;
      int n = arr.size();
      for (int i = 1; i < n; i++) {
         ret += 9 * A(9, i - 1);
      }
      set<int> visited;
      for (int i = 0; i < n; i++) {
         int digit = arr[i];
         for (int j = i == 0 ? 1 : 0; j < digit; j++) {
            if (visited.count(j))
            continue;
            ret += A(9 - i, n - i - 1);
         }
         if (visited.count(digit))
         break;
         visited.insert(digit);
      }
      return N - ret;
   }
};
main(){
   Solution ob;
   cout << (ob.numDupDigitsAtMostN(99));
}

Input

99

Output

9
raja
Published on 04-Jun-2020 14:22:10
Advertisements