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

后端 未结 16 2107
轻奢々
轻奢々 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:21

    this is coded in java...
    logic: say number is 34, binary equal-ant is 10010, which can be written as 10000 + 10. 10000 has 4 zeros, so count of all 1's before this number is 2^4(reason below). so count is 2^4 + 2^1 + 1(number it self). so answer is 35.
    *for binary number 10000. total combinations of filling 4 places is 2*2*2*2x2(one or zero). So total combinations of ones is 2*2*2*2.

    public static int getOnesCount(int number) {
        String binary = Integer.toBinaryString(number);
        return getOnesCount(binary);
    }
    
    private static int getOnesCount(String binary) {
        int i = binary.length();
    
        if (i>0 && binary.charAt(0) == '1') {
            return gePowerof2(i) + getOnesCount(binary.substring(1));
        }else if(i==0)
            return 1;
        else
            return getOnesCount(binary.substring(1));
    
    }
    //can be replaced with any default power function
    private static int gePowerof2(int i){
        int count = 1;
        while(i>1){
            count*=2;
            i--;
        }
        return count;
    }
    

提交回复
热议问题