Find the number of integers from 1 to n which contains digits 0’s and 1’s only in C++

C++Server Side ProgrammingProgramming

Suppose, we have a number n. Our task is to find the number of integers from 1 to n, which contains digits 0s and 1s only. So if n = 15, then output will be. As the numbers are 1, 10, 11

To solve this, we will create integers using 0s and 1s using recursive function. Following code will help us to understand this better.

Example

 Live Demo

#include<iostream>
using namespace std;
int numberOfValues(int p, int n) {
   if (p > n)
      return 0;
   return 1 + numberOfValues(p * 10, n) + numberOfValues(p * 10 + 1, n);
}
int main() {
   int n = 120;
   cout << "Number of values using 0s and 1s: " << numberOfValues(1, n);
}

Output

Number of values using 0s and 1s: 7
raja
Published on 19-Dec-2019 11:56:07
Advertisements