Count of Binary Digit numbers smaller than N in C++

C++Server Side ProgrammingProgramming

Given an integer N as input. The goal is to find the count of integers that are less than N and represented in Binary form. For example if input N is 12 then numbers less than 12 are 1,10,11 that are binary and contain 0s and 1s as digits. The answer would be 3.

For Example

Input

N=100

Output

Count of Binary Digit numbers smaller than N are − 4

Explanation

The Binary numbers less than 100 are − 1, 10, 11, 100

Input

N=120

Output

Count of Binary Digit numbers smaller than N are: 7

Explanation

The Binary numbers less than 100 are : 1, 10, 11, 100, 101, 110, 111

Approach used in the below program is as follows

In this approach we will use an integer vector vec. To this we will first push 1. Now to generate the next binary number we will extract the last number (temp) from vec (Initially 1). Then generate next using: temp*10 and temp*10+1 as binary numbers will always be ( 1,10,11,100,110,111….). Pop numbers from vec and if it is less than N then increment count.

  • Take an integer N as input.

  • Function Smaller_N(int N) takes N and returns a count of Binary Digit numbers smaller than N.

  • Take the initial count as 0.

  • Take integer vector vec for storing integers that contain 0s and 1s only.

  • Add 1 to the vector using vec.push_back(1).

  • Using while loop, traverse vec[ ] and take out last pushed as temp= vec.back(). And remove it from vec.

  • If temp<=N, then increment count and generate next binary integer as temp*10 and temp*10+1 and add to vec.

  • At the end of while return count as a result.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int Smaller_N(int N){
   int count = 0;
   vector<int> vec;
   vec.push_back(1);
   while (!vec.empty()){
      int temp = vec.back();
      vec.pop_back();
      if (temp <= N){
         count++;
         int temp_2 = temp * 10;
         vec.push_back(temp_2);
         vec.push_back(temp_2 + 1);
      }
   }
   return count;
}
int main(){
   int N = 1000;
   cout<<"Count of Binary Digit numbers smaller than N are: "<<Smaller_N(N);
   return 0;
}

Output

If we run the above code it will generate the following output −

Count of Binary Digit numbers smaller than N are: 8
raja
Published on 05-Jan-2021 11:43:50
Advertisements