Count of integers up to N which represent a Binary number | Python3 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
from math import * NEW_LINE def countBinaries ( N ) : NEW_LINE INDENT ctr = 1 NEW_LINE ans = 0 NEW_LINE while ( N > 0 ) : NEW_LINE INDENT if ( N % 10 == 1 ) : NEW_LINE INDENT ans += pow ( 2 , ctr - 1 ) NEW_LINE DEDENT elif ( N % 10 > 1 ) : NEW_LINE INDENT ans = pow ( 2 , ctr ) - 1 NEW_LINE DEDENT ctr += 1 NEW_LINE N //= 10 NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 20 NEW_LINE print ( int ( countBinaries ( N ) ) ) NEW_LINE DEDENT