The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integersx
andy
, return the Hamming distance between them.
해당하는(corresponding) 심볼들이 서로 다른 위치의 수
Input: x = 1, y = 4
Output: 2
Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.
Input: x = 3, y = 1
Output: 1
XOR
을 사용하면 좋을 거 같다import timeit
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
def decimal_to_binary(num, bit = 8):
result = ""
while num > 0:
result = str(num % 2) + result
num //= 2
return result.rjust(bit, "0") if bit > 0 else result
return decimal_to_binary(x ^ y, 0).count("1")
def hammingDistance2(self, x: int, y: int) -> int:
return bin(x ^ y).count("1")
s = Solution()
""" print(s.hammingDistance(1, 4))
print(s.hammingDistance(3, 1))
print(s.hammingDistance(0, 0))
print(s.hammingDistance(30, 2147483647))"""
print(timeit.timeit(lambda: s.hammingDistance(30, 2147483647), number=100000)) # 0.9807200999999999
print(timeit.timeit(lambda: s.hammingDistance2(30, 2147483647), number=100000)) # 0.04811129999999997
Runtime: 28 ms
Memory Usage: 14.2 MB
# 12 ms
def hammingDistance3(self, x: int, y: int) -> int:
m = max(x, y)
n = min(x, y)
bits = 0
while m:
r1 = m % 2 == 0
r2 = n % 2 == 0
if r1 != r2:
bits += 1
m >>= 1
n >>= 1
return bits
# 16 ms
def hammingDistance4(self, x: int, y: int) -> int:
res = x^y
count = 0
for i in range(32):
if res&1:
count+=1
res = res>>1
return count
bin().count()
사용보다 더 빠르다고 나와 있는데 timeit
으로 테스트 해보면 그렇지가 않다print(timeit.timeit(lambda: s.hammingDistance(43243, 2147483647), number=10000)) # 0.08998709999999999
print(timeit.timeit(lambda: s.hammingDistance2(43243, 2147483647), number=10000)) # 0.005768099999999998
print(timeit.timeit(lambda: s.hammingDistance3(43243, 2147483647), number=10000)) # 0.06952909999999998
print(timeit.timeit(lambda: s.hammingDistance4(43243, 2147483647), number=10000)) # 0.0418421000000000
time
으로 체크해봐도 bin()
사용하는 hammingDistance2
가 가장 빠르다.