Python | Count a set of bits in a range

Python Methods and Functions

Restriction: 1 & lt; = l & lt; = r & lt; = number of bits in binary n .

Examples:

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

We have a solution for this problem, please refer to Number set 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 given bits between them.
  • # Function to count the set bits in the range

      

    def countSetBits (n, l, r):

     

    # convert n to binary

      binary = bin (n)

     

    # remove first two characters

      binary = binary [ 2 :]

     

    # backward string

    binary = binary [ - 1 :: - 1 ]

     

      # read all set bits "1" starting from index l-1

    # to r where r is exclusive

    print ( len ([binary [ i] for i in range (l - 1 , r) if binary [i] = = '1' ]))

     
    # Driver program

    if   __ name__ = = "__ main__" :

    n = 42

    l = 2

      r = 5

    countSetBits (n, l, r)

    Output:

     2 




    Tutorials