Count total set bits in all numbers from 1 to n | Returns position of leftmost set bit . The rightmost position is considered as 0 ; Given the position of previous leftmost set bit in n ( or an upper bound onleftmost position ) returns the new position of leftmost set bit in n ; The main recursive function used by countSetBits ( ) def _countSetBits ( n , m ) Returns count of set bits present in all numbers from 1 to n ; Get the position of leftmost set bit in n . This will be used as an upper bound for next set bit function ; Use the position ; Base Case : if n is 0 , then set bit count is 0 ; get position of next leftmost set bit ; If n is of the form 2 ^ x - 1 , i . e . , if n is like 1 , 3 , 7 , 15 , 31 , . . etc , then we are done . Since positions are considered starting from 0 , 1 is added to m ; update n for next recursive call ; Driver code
def getLeftmostBit ( n ) : NEW_LINE INDENT m = 0 NEW_LINE while ( n > 1 ) : NEW_LINE INDENT n = n >> 1 NEW_LINE m += 1 NEW_LINE DEDENT return m NEW_LINE DEDENT def getNextLeftmostBit ( n , m ) : NEW_LINE INDENT temp = 1 << m NEW_LINE while ( n < temp ) : NEW_LINE INDENT temp = temp >> 1 NEW_LINE m -= 1 NEW_LINE DEDENT return m NEW_LINE DEDENT def countSetBits ( n ) : NEW_LINE INDENT m = getLeftmostBit ( n ) NEW_LINE return _countSetBits ( n , m ) NEW_LINE DEDENT def _countSetBits ( n , m ) : NEW_LINE INDENT if ( n == 0 ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT m = getNextLeftmostBit ( n , m ) NEW_LINE if ( n == ( 1 << ( m + 1 ) ) - 1 ) : NEW_LINE INDENT return ( ( m + 1 ) * ( 1 << m ) ) NEW_LINE DEDENT n = n - ( 1 << m ) NEW_LINE return ( n + 1 ) + countSetBits ( n ) + m * ( 1 << ( m - 1 ) ) NEW_LINE DEDENT n = 17 NEW_LINE print ( " Total ▁ set ▁ bit ▁ count ▁ is " , countSetBits ( n ) ) NEW_LINE