[Geeks for Geeks] Count Total Setbits

Count Total Setbits

You are given a number N. Find the total number of setbits in the numbers from 1 to N.

  • Time : O(lgn)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
class Solution{
public:
int countBits(int n){
if(n <= 1) return n;
int lg = log2(n);
int res = lg * (1<<(lg-1)) + n - (1<<lg) + 1;
return res + countBits(n ^ (1<<lg));
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/21/PS/GeeksforGeeks/sherlock-and-his-enemies/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.