728x90
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
distance = 0
z = x ^ y
while z:
distance += 1
z &= z - 1
return distance
def hammingDistance2(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')
2번째 솔루션
비트 XOR 연산으로 position이 서로 다른지 확인한다.
x = 1, y = 4일 경우
001
XOR
100
= 101
이 str에서 count메서드를 사용해서 1의 횟수를 return
출처: github.com/jiapengwen/LeetCode/blob/master/Python/hamming-distance.py
728x90
'Leetcode' 카테고리의 다른 글
[LeetCode] Number Complement 파이썬 (format, bitwise) (0) | 2021.04.19 |
---|---|
[LeetCode] Island Perimeter 파이썬 (island, traverse) (0) | 2021.04.19 |
[LeetCode] Repeated Substring Pattern 파이썬 (KMP) (0) | 2021.04.18 |
[LeetCode] Assign Cookies 파이썬 (greedy) (0) | 2021.04.17 |
[LeetCode] Find All Numbers Disappeared in an Array 파이썬(set.difference) (0) | 2021.04.16 |
댓글