Finding the total number of set-bits from 1 to n

后端 未结 16 2058
轻奢々
轻奢々 2020-12-04 09:54

Write an algorithm to find F(n) the number of bits set to 1, in all numbers from 1 to n for any given value of n.

Complexity should be O(log n)

16条回答
  •  -上瘾入骨i
    2020-12-04 10:18

    I know this post came in late to the party, please find logn solution below:

    static int countSetBitWithinRange(int n)
    {
        int x = n + 1, index = 0, count = 0;
        int numberOfOnesInAGroup = (int)Math.pow(2, index);
        while(x >= numberOfOnesInAGroup)
        {
            int countOfZeroOnePairs = (x / numberOfOnesInAGroup);
            int numberOfPairsOfZerosAndOnes = countOfZeroOnePairs / 2;
            int numberOfSetBits = numberOfPairsOfZerosAndOnes * numberOfOnesInAGroup;
            //If countOfZeroOnePairs is even then the pairs are complete else there will be ones that do not have a corresponding zeros pair
            int remainder = (countOfZeroOnePairs % 2 == 1) ? (x % numberOfOnesInAGroup) : 0;
            count = count + numberOfSetBits + remainder;
            numberOfOnesInAGroup = 1 << ++index;
        }
        return count;
    }
    

提交回复
热议问题