Skip to content

Commit 9870def

Browse files
committed
add solution : 191. Number of 1 Bits
1 parent 2496829 commit 9870def

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

โ€Žnumber-of-1-bits/mmyeon.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* @link https://leetcode.com/problems/number-of-1-bits/description/
3+
*
4+
* ์ ‘๊ทผ ๋ฐฉ๋ฒ• :
5+
* - n์„ 2๋กœ ๋‚˜๋ˆ„๋ฉด์„œ ๋‚˜๋จธ์ง€๊ฐ€ 1์ธ ๊ฒฝ์šฐ ์นด์šดํŠธ๋ฅผ ์—…๋ฐ์ดํŠธํ•œ๋‹ค.
6+
*
7+
* ์‹œ๊ฐ„๋ณต์žก๋„ : O(log(n))
8+
* - ์ˆซ์ž์˜ ๋น„ํŠธ ๊ธธ์ด๋งŒํผ ๋ฐ˜๋ณต
9+
*
10+
* ๊ณต๊ฐ„๋ณต์žก๋„ : O(1)
11+
* - ๊ณ ์ •๋œ ๋ณ€์ˆ˜๋งŒ ์‚ฌ์šฉ
12+
*/
13+
function hammingWeight(n: number): number {
14+
let bitCount = 0;
15+
while (n >= 1) {
16+
bitCount += n % 2;
17+
18+
n = Math.floor(n / 2);
19+
}
20+
21+
return bitCount;
22+
}
23+
24+
// ๋น„ํŠธ ์—ฐ์‚ฐ์ž ํ™œ์šฉํ•˜๋Š” ๋ฐฉ๋ฒ•
25+
function hammingWeight(n: number): number {
26+
let bitCount = 0;
27+
while (n >= 1) {
28+
bitCount += n & 1;
29+
30+
n >>>= 1;
31+
}
32+
33+
return bitCount;
34+
}

0 commit comments

Comments
ย (0)