Skip to content

Commit bdc238b

Browse files
authored
feat: add nums of 1 bits solution
1 parent db46313 commit bdc238b

1 file changed

Lines changed: 28 additions & 0 deletions

File tree

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution:
2+
def hammingWeight(self, n: int) -> int:
3+
"""
4+
์ฃผ์–ด์ง„ ์ˆซ์ž์˜ ์ด์ง„ ํ‘œํ˜„์—์„œ, 1์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ณ„์‚ฐํ•˜๋Š” ํ•จ์ˆ˜
5+
์˜ˆ) 11 -> 1011 => 3
6+
7+
๋ฐฉ๋ฒ•:
8+
1. ์ˆซ์ž๋ฅผ ์ด์ง„๋ฒ•์œผ๋กœ ๋ฐ”๊ฟ”์„œ 1์„ ์ฐพ์•„ ๊ณ„์‚ฐํ•˜๊ธฐ
9+
- ์ด์ง„๋ฒ•์œผ๋กœ ๋ฐ”๊พธ๋Š” ๊ณผ์ •์—์„œ ์ „์ฒด ์ˆœํšŒ๋ฅผ ํ•˜๊ณ , 1์„ ์ฐพ์„๋•Œ ๋˜ ์ˆœํšŒํ•ด์•ผํ– .
10+
-> ํ•œ๋ฒˆ์— ํ•ด๊ฒฐํ•  ์ˆ˜ ์—†์„๊นŒ?
11+
2. ์ˆซ์ž๋ฅผ ์ง์ ‘ ๋น„ํŠธ์—ฐ์‚ฐํ•˜๋ฉฐ ๊ณ„์‚ฐํ•˜๊ธฐ
12+
- ์ˆซ์ž๋ฅผ bitshiftํ•˜๋ฉด์„œ ๋งˆ์ง€๋ง‰ ๋น„ํŠธ๊ฐ€ 1์ธ์ง€ ์•„๋‹Œ์ง€ ์ฐพ๊ธฐ
13+
- 1์ด๋ฉด count + 1
14+
-> ์‹œ๊ฐ„ ๋ณต์žก๋„ O(k) (k๋Š” ๋น„ํŠธ๊ธธ์ด), ๊ณต๊ฐ„๋ณต์žก๋„ O(1)
15+
16+
Args:
17+
n(int): ์–‘์ˆ˜
18+
19+
Returns:
20+
int: ์ด์ง„ ํ‘œํ˜„์—์„œ 1์˜ ๊ฐœ์ˆ˜
21+
"""
22+
curr = n
23+
count = 0
24+
while curr > 0:
25+
if curr & 1 == 1:
26+
count += 1
27+
curr = curr >> 1
28+
return count

0 commit comments

Comments
ย (0)