Skip to content

Commit 817a0fc

Browse files
committed
add number of 1 bits solution
1 parent 9707c83 commit 817a0fc

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

number-of-1-bits/Tessa1217.java

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
/** 주어진 숫자의 Hamming weight 구하기 */
2+
class Solution {
3+
4+
// 시간복잡도: O(1), 공간복잡도: O(1), 비트 연산자 사용
5+
public int hammingWeight(int n) {
6+
int count = 0;
7+
while (n != 0) {
8+
count += (n & 1);
9+
n >>>= 1;
10+
}
11+
return count;
12+
}
13+
14+
// 시간복잡도: O(1), 공간복잡도: O(1)
15+
// public int hammingWeight(int n) {
16+
17+
// int count = 0;
18+
// while (n != 0) {
19+
// if (n % 2 == 1) {
20+
// count++;
21+
// }
22+
// n /= 2;
23+
// }
24+
// return count;
25+
// }
26+
27+
// 시간복잡도: O(1), 공간복잡도: O(n)
28+
// public int hammingWeight(int n) {
29+
// return Integer.toBinaryString(n).replaceAll("0", "").length();
30+
// }
31+
}
32+

0 commit comments

Comments
 (0)