-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathsolution.java
More file actions
25 lines (19 loc) · 759 Bytes
/
Copy pathsolution.java
File metadata and controls
25 lines (19 loc) · 759 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public static int countSetBits(int n) {
long total = 0; // use long for safety in calculation
// loop over bit positions
for (int i = 0; (1L << i) <= n; i++) {
long bitMask = 1L << i; // 2^i
long cycleLen = bitMask << 1; // 2^(i+1)
long fullCycles = n / cycleLen; // complete pattern blocks
// in each full cycle, bit i is '1' exactly bitMask times
total += fullCycles * bitMask;
long remainder = n % cycleLen; // leftover part
long extraOnes = remainder - bitMask + 1;
if (extraOnes > 0) {
total += extraOnes;
}
}
return (int) total;
}
}