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.
#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); }
Number of values using 0s and 1s: 7