Skip to content

Commit 3ef3696

Browse files
committed
number of 1 bits solution
1 parent d0000e8 commit 3ef3696

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

โ€Žnumber-of-1-bits/wooseok123.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
let hammingWeight = function (n) {
2+
return DecToBinAndGetSetBits(n);
3+
};
4+
5+
// TC : O(log n) | SC : O(1)
6+
7+
let DecToBinAndGetSetBits = (n) => {
8+
let targetNum = n;
9+
let result = 0;
10+
while (targetNum > 0) {
11+
let remainder = targetNum % 2;
12+
if (remainder === 1) result += 1;
13+
targetNum = parseInt(targetNum / 2);
14+
}
15+
return result;
16+
};
17+
18+
// TC : O(log n) | SC : O(log n)
19+
// ๊ทผ๋ฐ ์‚ฌ์‹ค split ๋ฉ”์„œ๋“œ ์ž์ฒด๋Š” o(n)์ธ๋ฐ, toString๊ณผ์ •์„ ํ†ตํ•ด log(n)์˜ ๊ฐœ์ˆ˜๋งŒํผ ๋‚˜์™€๋ฒ„๋ฆฐ ๊ฒƒ์ด๋ฉด o(log n)์ด๋ผ๊ณ  ํ‘œ๊ธฐํ•ด๋„ ๋˜๋Š”๊ฑธ๊นŒ?
20+
21+
// let DecToBinAndGetSetBits = (n) => {
22+
// let target = n;
23+
// let bin = n.toString(2);
24+
// return bin.split("").filter((el) => el == 1).length
25+
// }
26+
27+
// TC : O(log n) | SC : O(log n)
28+
29+
// let DecToBinAndGetSetBits = (n) => {
30+
// let target = n;
31+
// let bin = n.toString(2);
32+
// let matches = bin.match(/1/g);
33+
// return matches.length
34+
// }

0 commit comments

Comments
ย (0)