Skip to content

Commit af85fa8

Browse files
author
jinvicky
committed
number of 1 bits solution
1 parent e30c057 commit af85fa8

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

number-of-1-bits/jinvicky.java

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
// [sol1] 반복문을 사용하면서 ((n>>i) & 1) == 1를 만족하는 개수를 구한다.
3+
public int hammingWeight(int n) {
4+
int answer = 0;
5+
for(int i = 0; i < 32; i++) {
6+
// >> 연산자를 이용하여 값을 오른쪽으로 bitwise 연산을 한다.
7+
if(((n>>i) & 1) == 1) {
8+
answer+=1;
9+
}
10+
}
11+
return answer;
12+
}
13+
14+
// [sol2] 자바를 사용한다면 1개의 메서드, 1줄의 코드로 해결할 수 있다.
15+
public int hammingWeight2 (int n) {
16+
return Integer.bitCount(n);
17+
}
18+
}

0 commit comments

Comments
 (0)