Count of integers up to N which represent a Binary number | 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
function countBinaries ( N ) { let powersOfTwo = [ ] ; powersOfTwo . push ( 1 ) ; for ( let i = 1 ; i < 11 ; i ++ ) { powersOfTwo . push ( powersOfTwo [ i - 1 ] * 2 ) ; } let ctr = 1 ; let 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 ; } let N = 20 ; document . write ( countBinaries ( N ) ) ;