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 ; 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 ) { int ctr = 1 ; int ans = 0 ; while ( N > 0 ) { if ( N % 10 == 1 ) { ans += Math . pow ( 2 , ctr - 1 ) ; } else if ( N % 10 > 1 ) { ans = ( int ) ( Math . pow ( 2 , ctr ) - 1 ) ; } ctr ++ ; N /= 10 ; } return ans ; } public static void main ( String [ ] args ) { int N = 20 ; System . out . print ( countBinaries ( N ) ) ; } }