- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Find the number of integers from 1 to n which contains digits 0’s and 1’s only in C++
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
#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
Advertisements