Skip to content

Commit f6ed285

Browse files
committed
number-of-1-bitsํ’€์ด
1 parent d5e5a44 commit f6ed285

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

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

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
"""
2+
๋ฌธ์ œ ์š”์•ฝ
3+
- 32๋น„ํŠธ ๋ถ€ํ˜ธ ์—†๋Š” ์ •์ˆ˜ n์˜ ์ด์ง„ ํ‘œํ˜„์—์„œ '1'์˜ ๊ฐœ์ˆ˜(= set bits)๋ฅผ ๊ตฌํ•˜๋ผ.
4+
5+
์•„์ด๋””์–ด A: ๋ธŒ๋ผ์ด์–ธ ์ปค๋‹ˆํ•ธ(Brian Kernighan) ์•Œ๊ณ ๋ฆฌ์ฆ˜
6+
- ํ•ต์‹ฌ ๊ด€์ฐฐ: n & (n - 1)์€ n์˜ ์ตœํ•˜์œ„ 1๋น„ํŠธ๋ฅผ '0'์œผ๋กœ ๋งŒ๋“ ๋‹ค.
7+
์˜ˆ) n = 0b101100 โ†’ n-1 = 0b101011 โ†’ n & (n-1) = 0b101000 (์ตœํ•˜์œ„ 1 ํ•˜๋‚˜ ์‚ญ์ œ)
8+
- ๋”ฐ๋ผ์„œ '1'์˜ ๊ฐœ์ˆ˜๋งŒํผ ๋ฃจํ”„๊ฐ€ ๋ˆ๋‹ค.
9+
- ์‹œ๊ฐ„๋ณต์žก๋„: O(k) (k = n์˜ 1๋น„ํŠธ ๊ฐœ์ˆ˜) โ† ๋งค์šฐ ๋น ๋ฆ„
10+
- ๊ณต๊ฐ„๋ณต์žก๋„: O(1)
11+
"""
12+
13+
class Solution:
14+
def hammingWeight(self, n: int) -> int:
15+
cnt = 0
16+
while n:
17+
n &= n - 1 # ์ตœํ•˜์œ„ 1๋น„ํŠธ ์ œ๊ฑฐ
18+
cnt += 1
19+
return cnt

โ€Žvalid-palindrome/socow.pyโ€Ž

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,4 +12,4 @@
1212
class Solution:
1313
def isPalindrome(self, s: str) -> bool:
1414
cleaned = [c for c in s.lower() if c.isalnum()]
15-
return cleaned == cleaned[::-1]
15+
return cleaned == cleaned[::-1]

0 commit comments

Comments
ย (0)