-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path338.counting-bits.java
More file actions
41 lines (36 loc) · 875 Bytes
/
338.counting-bits.java
File metadata and controls
41 lines (36 loc) · 875 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
/*
* @lc app=leetcode id=338 lang=java
*
* [338] Counting Bits
*/
// @lc code=start
import java.util.ArrayList;
import java.util.HashMap;
class Solution {
// public int[] countBits(int n) {
// ArrayList<Integer> res = new ArrayList<>();
// for (int i = 0; i <= n; i++) {
// int currentNum = i;
// int currentOnesCount = 0;
// for (int j = 0; j < 32; j++) {
// if (currentNum == 0) {
// break;
// }
// if (currentNum % 2 == 1) {
// currentOnesCount++;
// }
// currentNum = currentNum >> 1;
// }
// res.add(currentOnesCount);
// }
// return res.stream().mapToInt(i -> i).toArray();
// }
public int[] countBits(int n) {
int[] ans = new int[n + 1];
for (int i = 1; i <= n; i++) {
ans[i] = ans[i >> 1] + (i & 1);
}
return ans;
}
}
// @lc code=end