Python Map Function | Count the total number of bits in all numbers from 1 to n

Counters | Python Methods and Functions

Examples:

 Input: n = 3 Output: 4 Binary representations are 1, 2 and 3 1, 10 and 11 respectively. Total set bits are 1 + 1 + 2 = 4. Input: n = 6 Output: 9 Input: n = 7 Output: 12 Input: n = 8 Output: 13 

We have solution to this problem, please refer to the map () function. The approach is very simple,

  1. Write a function that first converts a number to binary using

    # Function for calculating the total number of set bits in all numbers
    # from 1 to n

      
    # custom function

    def countSetBit (num):

      

      # convert decimal to binary and

    # count all 1s in it

    binary = bin (num)

     

    return len ([ch for ch in binary if ch = = '1' ])

     
    # function that counts the set bits in each number

    def countSetBitAll ( input ) :

     

    # card counting function per issue

      print ( sum ( map (countSetBit, input )))

     
    # Driver program

    if __ name__ = = "__ main__ " :

      n = 8

    input = []

      for i in range ( 1 , n + 1 ):

    input . append (i)

    countSetBitAll ( input )

    Output:

     13 




Tutorials