Count total set bits in all numbers from range L to R | Function that counts the set bits from 0 to N ; To store sum of set bits from 0 - N ; Until n >= to 2 ^ i ; This k will get flipped after 2 ^ i iterations ; Change is iterator from 2 ^ i to 1 ; This will loop from 0 to n for every bit position ; When change = 1 flip the bit ; Again set change to 2 ^ i ; Increment the position ; Function that counts the set bit in the range ( L , R ) ; Return the count ; Driver Code ; Given L and R ; Function Call
def countSetBit ( n ) : NEW_LINE INDENT i = 0 ; NEW_LINE ans = 0 ; NEW_LINE while ( ( 1 << i ) <= n ) : NEW_LINE INDENT k = True ; NEW_LINE change = 1 << i ; NEW_LINE for j in range ( n + 1 ) : NEW_LINE INDENT ans += 0 if k == True else 1 ; NEW_LINE if ( change == 1 ) : NEW_LINE INDENT k = False if k == True else True ; NEW_LINE change = 1 << i ; NEW_LINE DEDENT else : NEW_LINE INDENT change -= 1 ; NEW_LINE DEDENT DEDENT i += 1 ; NEW_LINE DEDENT return ans ; NEW_LINE DEDENT def countSetBits ( L , R ) : NEW_LINE INDENT return abs ( countSetBit ( R ) - countSetBit ( L - 1 ) ) ; NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT L = 3 ; NEW_LINE R = 5 ; NEW_LINE print ( " Total ▁ set ▁ bit ▁ count ▁ is ▁ " , countSetBits ( L , R ) ) ; NEW_LINE DEDENT