Skip to content

Commit c826585

Browse files
committed
number of 1 bits solution
1 parent 15d4682 commit c826585

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

β€Žnumber-of-1-bits/Yn3-3xh.java

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
/**
2+
[λ¬Έμ œν’€μ΄]
3+
- μ£Όμ–΄μ§„ μ–‘μ˜ μ •μˆ˜λ₯Ό 2μ§„μˆ˜λ‘œ λ³€ν™˜ν•˜μ—¬, 1의 개수 κ΅¬ν•˜κΈ°
4+
5+
- 풀이 1
6+
time: O(log N), space: O(1)
7+
class Solution {
8+
public int hammingWeight(int n) {
9+
int count = 0;
10+
while (n > 0) {
11+
if (n % 2 != 0) {
12+
count++;
13+
}
14+
n /= 2;
15+
}
16+
return count;
17+
}
18+
}
19+
- 풀이 2
20+
time: O(log N), space: O(1)
21+
22+
[회고]
23+
`n >> 1`λΉ„νŠΈ μ—°μ‚°μžλŠ” `n / 2` 와 κ°™λ‹€.
24+
`n >> 1`둜 ν’€λ©΄ 비ꡐ도 λΉ„νŠΈλ‘œ!
25+
26+
이진 ν‘œν˜„μ—μ„œ 1의 개수λ₯Ό μ„Έμ–΄μ£ΌλŠ” Integer.bitCount() λ©”μ„œλ“œλ„ μžˆμ—ˆλ‹€.
27+
*/
28+
class Solution {
29+
public int hammingWeight(int n) {
30+
int count = 0;
31+
while (n > 0) {
32+
if ((n & 1) == 1) {
33+
count++;
34+
}
35+
n >>= 1;
36+
}
37+
return count;
38+
}
39+
}

0 commit comments

Comments
Β (0)