Skip to content

Commit 0199703

Browse files
committed
number-of-1-bits solution (py, ts)
1 parent d3ef18f commit 0199703

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

number-of-1-bits/hi-rachel.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# O(log n) time, O(1) space
2+
# % 나머지, // 몫
3+
4+
class Solution:
5+
def hammingWeight(self, n: int) -> int:
6+
cnt = 0
7+
8+
while n > 0:
9+
if (n % 2) == 1:
10+
cnt += 1
11+
n //= 2
12+
13+
return cnt
14+
15+
16+
# O(log n) time, O(log n) space
17+
class Solution:
18+
def hammingWeight(self, n: int) -> int:
19+
return bin(n).count("1")
20+
21+
22+
# TS 풀이
23+
# O(log n) time, O(log n) space
24+
# function hammingWeight(n: number): number {
25+
# return n.toString(2).split('').filter(bit => bit === '1').length;
26+
# };

0 commit comments

Comments
 (0)