  Python | Counting unset bits in a range

Counters | Python Methods and Functions

Examples:

Input: n = 42, l = 2, r = 5 Output: 2 (42) 10 = (1  0101  0) 2 There are '2 'unset bits in the range 2 to 5. Input: n = 80, l = 1, r = 4 Output: 4

We have a solution to this problem, please refer to counter of unset bits in link bin (num) .

• Now remove the first two characters of the output binary string, because the bin function by default prefixes "0b" to the output string.
• Truncate the string starting at index ( l-1) to index r, and reverse it, then count the unset bits between them.
•  # Function for counting undefined bits in a range    def unsetBits (n, l, r):   # convert n to binary  < / code> binary = bin (n)   # remove first two characters binary = binary [ 2 :]   # backward string binary = binary [ - 1 :: - 1 ]    # read all unset bits "0" starting from index l-1 # up to r, where r is exclusive print ( len ([binary [i] for i in range (l - 1 , r) if binary [i] = = '0' ]))   # Driver program if __ name__ = = " __ main__ " :   n = 42 l = 2 r = 5 unsetBits (n, l, r)

Output:

2