-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCountingBits.java
More file actions
executable file
·43 lines (39 loc) · 967 Bytes
/
Copy pathCountingBits.java
File metadata and controls
executable file
·43 lines (39 loc) · 967 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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package bitwise;
public class CountingBits {
// 1.使用API
public int[] countBits1(int num) {
int[] res = new int[num + 1];
for (int i = 0; i <= num; i++) {
res[i] = Integer.bitCount(i);
}
return res;
}
// 直接运算
public int[] countBits2(int num) {
int[] res = new int[num + 1];
for (int i = 0; i <= num; i++) {
res[i] = countOnes(i);
}
return res;
}
public int countOnes(int x) {
int ones = 0;
while (x > 0) {
x &= (x - 1);
ones++;
}
return ones;
}
// 3.动态规划
public int[] countBits3(int num) {
int[] bits = new int[num + 1];
int highBit = 0;
for (int i = 1; i <= num; i++) {
if ((i & (i - 1)) == 0) {
highBit = i;
}
bits[i] = bits[i - highBit] + 1;
}
return bits;
}
}