Skip to content

Commit 77a3088

Browse files
committed
[7th batch] week 3 - number of 1 bits
1 parent ec750c0 commit 77a3088

1 file changed

Lines changed: 24 additions & 0 deletions

File tree

โ€Žnumber-of-1-bits/liza0525.pyโ€Ž

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,3 +20,27 @@ def hammingWeight(self, n: int) -> int:
2020
n = n // 2
2121

2222
return bits_sum
23+
24+
25+
# 7๊ธฐ ํ’€์ด
26+
# ์‹œ๊ฐ„ ๋ณต์žก๋„: O(log n)
27+
# - 2๋กœ ๊ณ„์† ๋‚˜๋ˆ„๊ณ , ์ด๋Š” 2์ง„์ˆ˜ ์ž๋ฆฟ์ˆ˜ ๋งŒํผ ๋ฐ˜๋ณต
28+
# ๊ณต๊ฐ„ ๋ณต์žก๋„: O(1)
29+
# - ๊ณ ์ •๋œ ๋ณ€์ˆ˜(quotient, remainder)๋งŒ ์‚ฌ์šฉ
30+
class Solution:
31+
def hammingWeight(self, n: int) -> int:
32+
# 10์ง„์ˆ˜๋ฅผ 2์ง„์ˆ˜๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ๊ณผ์ •์€ 2๋กœ ๊ณ„์† ๋‚˜๋ˆ„๋ฉด์„œ ๊ทธ ๋‚˜๋จธ์ง€ ๊ฐ’๋“ค์„ ์ˆœ์ฐจ์ ์œผ๋กœ ๋‚˜์—ดํ•˜๋Š” ๊ฒƒ์ด๋‹ค.
33+
# ์ด ๋•Œ ๋ฌธ์ž์—ด๋กœ ๋งŒ๋“ค์ง€ ์•Š๊ณ  ๋ฐ”๋กœ result์— ๋”ํ•ด๊ฐ€๋ฉด ๋‹ต์ด ๋  ์ˆ˜ ์žˆ์Œ
34+
result = 0
35+
36+
while n > 0:
37+
# ๋ชซ๊ณผ ๋‚˜๋จธ์ง€ ๊ณ„์‚ฐ
38+
quotient, remainder = n // 2, n % 2
39+
40+
# ๋‚˜๋จธ์ง€๋Š” result์— ๋”ํ•จ
41+
result += remainder
42+
43+
# ๋ชซ์€ ๋‹ค์Œ ํ”ผ์ œ์ˆ˜๋กœ ์‚ฌ์šฉ
44+
n = quotient
45+
46+
return result

0 commit comments

Comments
ย (0)