Count total set bits in all numbers from 1 to n

来源:互联网 发布:网络大型策略游戏 编辑:程序博客网 时间:2024/06/05 10:26

reference: 

http://www.geeksforgeeks.org/count-total-set-bits-in-all-numbers-from-1-to-n/


Problem Definition:

Given a positive integer n, count the total number of set bits in binary representation of all numbers from 1 to n.

Examples:

Input: n = 3Output:  4Input: n = 6Output: 9


Solution:

If the input number is of the form 2^b -1 e.g., 1,3,7,15.. etc, the number of set bits is b * 2^(b-1). This is because for all the numbers 0 to (2^b)-1, if you complement and flip the list you end up with the same list (half the bits are on, half off).

If the number does not have all set bits, then some position m is the position of leftmost set bit. The number of set bits in that position is n – (1 << m) + 1. The remaining set bits are in two parts:

1) The bits in the (m-1) positions down to the point where the leftmost bit becomes 0, and
2) The 2^(m-1) numbers below that point, which is the closed form above.

An easy way to look at it is to consider the number 6:

0|0 00|0 10|1 00|1 1-|–1|0 01|0 11|1 0

The leftmost set bit is in position 2 (positions are considered starting from 0). If we mask that off what remains is 2 (the "1 0" in the right part of the last row.) So the number of bits in the 2nd position (the lower left box) is 3 (that is, 2 + 1). The set bits from 0-3 (the upper right box above) is 2*2^(2-1) = 4. The box in the lower right is the remaining bits we haven't yet counted, and is the number of set bits for all the numbers up to 2 (the value of the last entry in the lower right box) which can be figured recursively.


Code:

// Returns count of set bits present in all numbers from 1 to nunsigned int countSetBits(unsigned int n){   // Get the position of leftmost set bit in n. This will be   // used as an upper bound for next set bit function   int m = getLeftmostBit (n);    // Use the position   return _countSetBits (n, m);} unsigned int _countSetBits(unsigned int n, int m){    // Base Case: if n is 0, then set bit count is 0    if (n == 0)       return 0;     /* get position of next leftmost set bit */    m = getNextLeftmostBit(n, m);     // 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    if (n == ((unsigned int)1<<(m+1))-1)        return (unsigned int)(m+1)*(1<<m);     // update n for next recursive call    n = n - (1<<m);    return (n+1) + countSetBits(n) + m*(1<<(m-1));}


原创粉丝点击