Count of Binary Digit numbers smaller than N | Python3 program to count all binary digit numbers smaller than N ; method returns count of binary digit numbers smaller than N ; queue to store all intermediate binary digit numbers ; binary digits start with 1 ; loop until we have element in queue ; push next binary digit numbers only if current popped element is N ; uncomment below line to print actual number in sorted order ; Driver code to test above methods
from collections import deque NEW_LINE def countOfBinaryNumberLessThanN ( N ) : NEW_LINE INDENT q = deque ( ) NEW_LINE q . append ( 1 ) NEW_LINE cnt = 0 NEW_LINE while ( q ) : NEW_LINE INDENT t = q . popleft ( ) NEW_LINE if ( t <= N ) : NEW_LINE INDENT cnt = cnt + 1 NEW_LINE q . append ( t * 10 ) NEW_LINE q . append ( t * 10 + 1 ) NEW_LINE DEDENT DEDENT return cnt NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT N = 200 NEW_LINE print ( countOfBinaryNumberLessThanN ( N ) ) NEW_LINE DEDENT