Skip to content

Commit 5c2fc91

Browse files
committed
number of 1 bits
1 parent 2dc5562 commit 5c2fc91

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

number-of-1-bits/YuuuuuuYu.java

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* Runtime: 0ms
3+
* Time Complexity: O(log n)
4+
* - n을 2로 나누는 과정을 반복하므로 log n에 비례
5+
*
6+
* Memory: 42.32MB
7+
* Space Complexity: O(1)
8+
*
9+
* Approach: 비트 연산 (나눗셈 방식)
10+
* 1) n을 2로 나눈 나머지(n%2)를 확인하여 1의 개수를 카운트
11+
* 2) 마지막에 1은 무조건 남기 때문에 while문 종료 후 1을 더해줌
12+
*/
13+
class Solution {
14+
public int hammingWeight(int n) {
15+
int count = 0;
16+
while (n > 1) {
17+
count += n%2;
18+
n /= 2;
19+
}
20+
21+
return count+1;
22+
}
23+
}

0 commit comments

Comments
 (0)