[Codewars] Count ones in a segment

Count ones in a segment

  • Time :
  • Space :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
long long dp(long long x) {
if(x == 0) return 1;
return dp(x-1) * 2 + (1ll<<x);
}
long long helper(long long x, long long bit, long long cnt, bool lo) {
if(bit == -1) return cnt;
if(lo) return cnt * (1ll<<(bit + 1)) + dp(bit);
if(x & (1ll<<bit)) return helper(x, bit - 1, cnt, true) + helper(x, bit - 1, cnt + 1, false);
return helper(x, bit - 1, cnt, false);
}
long long countOnes ( int left, int right )
{
return helper(right, 32, 0, 0) - helper(left-1, 32, 0, 0);
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/05/29/PS/Codewars/count-ones-in-a-segment/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.