Skip to content

Commit b036096

Browse files
committed
number of 1 bits
1 parent 950bb43 commit b036096

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
๋น„ํŠธ ์—ฐ์‚ฐ์„ ํ†ตํ•ด, 1์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฐฉ์‹
3+
์ˆซ์ž n -> N
4+
์‹œ๊ฐ„ ๋ณต์žก๋„ : O(logN)
5+
๊ณต๊ฐ„ ๋ณต์žก๋„ : O(1)
6+
*/
7+
class Solution2 {
8+
public int hammingWeight(int n) {
9+
int count = 0;
10+
long bit = 1;
11+
while(bit <= n) {
12+
if((n & bit) > 0) {
13+
count++;
14+
}
15+
bit <<= 1;
16+
}
17+
return count;
18+
}
19+
}
20+
21+
/**
22+
Integer.bitCount() ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ•ด, 1์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ๋ฐฉ์‹
23+
์‹œ๊ฐ„ ๋ณต์žก๋„ : O(1)
24+
๊ณต๊ฐ„ ๋ณต์žก๋„ : O(1)
25+
*/
26+
class Solution {
27+
public int hammingWeight(int n) {
28+
return Integer.bitCount(n);
29+
}
30+
}

0 commit comments

Comments
ย (0)