Count of integers up to N which represent a Binary number | Java 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
import java . util . * ; class GFG { static int countBinaries ( int N ) { Vector < Integer > powersOfTwo = new Vector < Integer > ( 11 ) ; powersOfTwo . add ( 1 ) ; for ( int i = 1 ; i < 11 ; i ++ ) { powersOfTwo . add ( powersOfTwo . get ( i - 1 ) * 2 ) ; } int ctr = 1 ; int ans = 0 ; while ( N > 0 ) { if ( N % 10 == 1 ) { ans += powersOfTwo . get ( ctr - 1 ) ; } else if ( N % 10 > 1 ) { ans = powersOfTwo . get ( ctr ) - 1 ; } ctr ++ ; N /= 10 ; } return ans ; } public static void main ( String [ ] args ) { int N = 20 ; System . out . print ( countBinaries ( N ) ) ; } }