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

后端 未结 16 2062
轻奢々
轻奢々 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条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-04 10:25

    Here is the java function

    private static int[] findx(int i) {
        //find the biggest power of two number that is smaller than i
        int c = 0;
        int pow2 = 1;
        while((pow2<< 1) <= i) {
            c++;
            pow2 = pow2 << 1;
        }
        return new int[] {c, pow2};
    }
    
    public static int TotalBits2(int number) {
        if(number == 0) {
            return 0;
        }
        int[] xAndPow = findx(number);
        int x = xAndPow[0];
        return x*(xAndPow[1] >> 1) + TotalBits2(number - xAndPow[1]) + number - xAndPow[1] + 1;
    }
    

提交回复
热议问题