
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
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
- Related Articles
- Find a Symmetric matrix of order N that contain integers from 0 to N-1 and main diagonal should contain only 0’s in C++
- Count number of binary strings of length N having only 0’s and 1’s in C++
- Count subarrays consisting of only 0’s and only 1’s in a binary array in C++
- Count subarrays with equal number of 1’s and 0’s in C++
- Find the Pattern of 1’s inside 0’s using C++
- Construct DFA of alternate 0’s and 1’s
- Largest number with binary representation is m 1’s and m-1 0’s in C++
- Find the index of first 1 in a sorted array of 0's and 1's in C++
- Count Numbers with N digits which consists of even number of 0's in C++
- Count Numbers with N digits which consists of odd number of 0's in C++
- Count the number of 1’s and 0’s in a binary array using STL in C++
- Maximum length of segments of 0’s and 1’s in C++
- Binary representation of next greater number with same number of 1’s and 0’s in C Program?
- Sort an arrays of 0’s, 1’s and 2’s using C++
- Sort an arrays of 0’s, 1’s and 2’s using Java

Advertisements