[LeetCode] #461. Hamming Distance

Fatboy Slim
1 min readMar 17, 2020

--

Environment: Python 3.7

Key technique: operator XOR ^, int to bit

Example:

Input: x = 1, y = 4Output: 2Explanation:
1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
The above arrows point to positions where the corresponding bits are different.

Analysis:

Find different in each bit and sum up them. We can use XOR to find different.

Solution:

class Solution:
def hammingDistance(self, x: int, y: int) -> int:
sum=0
xy=bin(x^y)
number_xy=xy[2:]
for i in number_xy:
sum+=int(i)
return sum

Submitted result:

--

--

Fatboy Slim
Fatboy Slim

Written by Fatboy Slim

Interesting in any computer science.

No responses yet