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

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

    Not sure if its late to reply, but here are my findings.

    Tried solving the problem with following approach, for number N every bitno ( from LSB to MSB, say LSB starts with bitno 1 and incrementing with next bit value) number of bits set can be calculated as , (N/(2 topower bitno) * (2 topower bitno-1) + { (N%(2 topower bitno)) - [(2 topower bitno-1) - 1] }

    Have written recursive function for it C/C++ please check. I am not sure but I think its complexity is log(N). Pass function 2 parameters, the number (no) for which we want bits to be calculated and second start count from LSB , value 1.

    int recursiveBitsCal(int no, int bitno){
    int res = int(no/pow(2,bitno))*int(pow(2,bitno-1));
    int rem1 = int(pow(2,bitno-1)) -1;
    int rem = no % int(pow(2,bitno));
    if (rem1 < rem) res += rem -rem1;
    if ( res <= 0 )
        return 0;
    else
        return res + recursiveBitsCal(no, bitno+1);
    }
    

提交回复
热议问题