Skip to content

Commit 521e923

Browse files
committed
add number of 1 bits solution
1 parent 8e138a4 commit 521e923

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
2+
// Time complexity: O(k)
3+
// Space complexity: O(k)
4+
5+
/**
6+
* @param {number} n
7+
* @return {number}
8+
*/
9+
10+
// λ¬Έμžμ—΄ λ³€ν™˜μ„ μ‚¬μš©ν•œ 풀이
11+
// μ΄μ§„μˆ˜λ‘œ λ³€ν™˜λœ 수λ₯Ό λ¬Έμžμ—΄λ‘œ λ³€ν™˜ν›„ 1의 개수λ₯Ό μ„ΈλŠ” 방법
12+
// λ¬Έμžμ—΄ λ³€ν™˜μ€ λΉ„νŠΈ μ—°μ‚°μžλ³΄λ‹€ λŠλ¦¬μ§€λ§Œ μ΄ν•΄ν•˜κΈ° μ‰¬μš΄ 방법
13+
var hammingWeight = function (n) {
14+
return n.toString(2).split('').filter(b => b === '1').length
15+
}
16+
17+
// Time complexity: O(1)
18+
// Space complexity: O(1)
19+
20+
// λΉ„νŠΈ μ—°μ‚°μžλ₯Ό μ‚¬μš©ν•œ 풀이
21+
// λΉ„νŠΈ μ—°μ‚°μžλŠ” μ΄μ§„μˆ˜λ‘œ λ³€ν™˜λœ 수λ₯Ό λΉ„κ΅ν•˜λŠ” μ—°μ‚°μž
22+
// μžλ°”μŠ€ν¬λ¦½νŠΈ 엔진이 숫자λ₯Ό 32λΉ„νŠΈ μ •μˆ˜λ‘œ λ³€ν™˜ν›„ CPU μˆ˜μ€€μ—μ„œ 연산을 μˆ˜ν–‰
23+
var hammingWeight = function (n) {
24+
let count = 0;
25+
for (let i = 0; i < 32; i++) {
26+
if ((n & (1 << i)) !== 0) {
27+
count++;
28+
}
29+
}
30+
return count;
31+
};

0 commit comments

Comments
Β (0)