[LeetCode][Python3] 191. Number of 1 Bits
2018. 11. 4. 17:29 |
프로그래밍/LeetCode
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
'프로그래밍 > LeetCode' 카테고리의 다른 글
[LeetCode][Python3] 237. Delete Node in a Linked List (0) | 2018.11.04 |
---|---|
[LeetCode][Python3] 217. Contains Duplicate (0) | 2018.11.04 |
[LeetCode][Python3] 204. Count Primes (0) | 2018.11.04 |
[LeetCode][Python3] 202. Happy Number (0) | 2018.11.04 |
[LeetCode][Python3] 190. Reverse Bits (0) | 2018.11.04 |
[LeetCode][Python3] 189. Rotate Array (0) | 2018.11.03 |
[LeetCode][Python3] 172. Factorial Trailing Zeroes (0) | 2018.11.03 |
[LeetCode][Python3] 171. Excel Sheet Column Number (0) | 2018.11.03 |
최근에 달린 댓글 최근에 달린 댓글