Skip to content

Commit b82a897

Browse files
counting bits solution
1 parent d21d14e commit b82a897

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

β€Žcounting-bits/jaejeong1.javaβ€Ž

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class SolutionCountingBits {
2+
public int[] countBits(int n) {
3+
// 0 ~ n κΉŒμ§€μ˜ 수λ₯Ό μ΄μ§„μˆ˜λ‘œ λ³€ν™˜ν•œλ‹€μŒ, 1의 개수λ₯Ό μΉ΄μš΄νŠΈν•΄ λ°°μ—΄λ‘œ λ°˜ν™˜
4+
// ν™€μˆ˜/짝수 μ—¬λΆ€λ₯Ό λ‚˜λˆ μ„œ 1의 개수λ₯Ό ꡬ함
5+
// ν™€μˆ˜: 이전 κ°’ + 1, 짝수: i / 2의 1의 κ°œμˆ˜μ™€ 같은 κ°’
6+
// μ‹œκ°„λ³΅μž‘λ„: O(N), κ³΅κ°„λ³΅μž‘λ„: O(N)
7+
8+
int[] countingBits = new int[n + 1];
9+
countingBits[0] = 0;
10+
11+
for (int i=1; i<=n; i++) {
12+
if (isOddNumber(i)) {
13+
countingBits[i] = countingBits[i - 1] + 1;
14+
} else {
15+
countingBits[i] = countingBits[i / 2];
16+
}
17+
}
18+
19+
return countingBits;
20+
}
21+
22+
// μ‹œκ°„λ³΅μž‘λ„: O(1)
23+
private boolean isOddNumber(int n) {
24+
return n % 2 == 1;
25+
}
26+
}

0 commit comments

Comments
Β (0)