Skip to content

Commit 6d46aaf

Browse files
committed
add number-of-1-bits solution
1 parent 0752d78 commit 6d46aaf

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

number-of-1-bits/jongwanra.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
"""
2+
[Problem]
3+
https://leetcode.com/problems/number-of-1-bits/description/
4+
5+
양수 n이 주어졌을 때, 이진법에서 1로 설정된 비트의 개수를 반환하는 함수를 작성해라.
6+
7+
8+
[Plan]
9+
1. 주어진 양수를 이진수로 변환한다.
10+
2. for-loop을 순회하며 1의 개수를 counting한다.
11+
12+
[Complexity]
13+
N: bin(n).length - 2
14+
Time: O(N)
15+
Space = O(N)
16+
"""
17+
class Solution:
18+
def hammingWeight(self, n: int) -> int:
19+
binary = bin(n)
20+
output = 0
21+
for index in range(2, len(binary)):
22+
if binary[index] == '1':
23+
output += 1
24+
return output
25+
"""
26+
ref: https://www.algodale.com/problems/number-of-1-bits/
27+
[Complexity]
28+
Time: O(log n)
29+
Space: O(1)
30+
"""
31+
class AnotherSolution:
32+
def hammingWeight(self, n: int) -> int:
33+
count = 0
34+
while n:
35+
quotient, remainder = divmod(n, 2)
36+
print(f"n = {n} quotient={quotient}, remainder={remainder}")
37+
count += remainder
38+
n = quotient
39+
return count
40+
41+
sol = AnotherSolution()
42+
print(sol.hammingWeight(11) == 3)
43+
print(sol.hammingWeight(128) == 1)
44+
print(sol.hammingWeight(2147483645) == 30)
45+

0 commit comments

Comments
 (0)