[InterviewBit] Count Total Set Bits

Count Total Set Bits

  • Time : O(logA)
  • Space : O(1)
1
2
3
4
5
6
7
8
9
int Solution::solve(int A) {
if(A <= 1) return A;
long long lg2 = log2(A), mask = 1<<lg2, mod = 1e9 + 7;
long long res = 0, shift = 0;

while((1<<shift) < mask) res = (res * 2 + (1<<shift++)) % mod;

return (res + ((A^mask) + 1) + solve(A ^ mask)) % mod;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/09/07/PS/interviewbit/count-total-set-bits/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.