Count of integers up to N which represent a Binary number | C ++ Program to count the number of integers upto N which are of the form of binary representations ; Function to return the count ; PreCompute and store the powers of 2 ; If the current last digit is 1 ; Add 2 ^ ( ctr - 1 ) possible integers to the answer ; If the current digit exceeds 1 ; Set answer as 2 ^ ctr - 1 as all possible binary integers with ctr number of digits can be obtained ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countBinaries ( int N ) { vector < int > powersOfTwo ( 11 ) ; powersOfTwo [ 0 ] = 1 ; for ( int i = 1 ; i < 11 ; i ++ ) { powersOfTwo [ i ] = powersOfTwo [ i - 1 ] * 2 ; } int ctr = 1 ; int ans = 0 ; while ( N > 0 ) { if ( N % 10 == 1 ) { ans += powersOfTwo [ ctr - 1 ] ; } else if ( N % 10 > 1 ) { ans = powersOfTwo [ ctr ] - 1 ; } ctr ++ ; N /= 10 ; } return ans ; } int main ( ) { int N = 20 ; cout << countBinaries ( N ) ; return 0 ; }