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

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

    Here is my solution to this. Time complexity : O (Log n)

    public int countSetBits(int n){
        int count=0;
        while(n>0){
            int i= (int)(Math.log10(n)/Math.log10(2));
            count+= Math.pow(2, i-1)*i;
            count+= n-Math.pow(2, i)+1;
            n-= Math.pow(2, i);
        }
        return count;
    }
    

提交回复
热议问题