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

后端 未结 16 2077
轻奢々
轻奢々 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条回答
  •  Happy的楠姐
    2020-12-04 10:29

    short and sweet!

     public static int countbits(int num){
        int count=0, n;
        while(num > 0){
            n=0;
            while(num >= 1<<(n+1))
                n++;
            num -= 1<

提交回复
热议问题