프로그래밍/LeetCode
[LeetCode][Python3] 191. Number of 1 Bits
snoopybox
2018. 11. 4. 17:29
Problem :
https://leetcode.com/problems/number-of-1-bits/
My Solution :
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
ans = 0
while n:
ans += n&1
n >>= 1
return ans
Comment :
위 방법은 단순히 shift 하면서 1을 세어보는 것이고, 아래 방법은 n & (n-1) 연산을 하게 되면 마지막 1이 제거된다는 성질을 이용한 것이다.
My Solution2 :
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
ans = 0
while n:
n &= n-1
ans += 1
return ans