leetcode461

461. Hamming Distance

Description

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.
Example:

1
2
3
4
5
6
7
8
9
10
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.

Idea

It’s involved with bits, which bring bit operations into my mind. — xor

Code

1
2
3
4
5
6
7
8
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x ^ y).count('1')

Python

bin() example:

1
2
3
4
5
number = 5
print('The binary equivalent of 5 is:', bin(number))

# result:
The binary equivalent of 5 is: 0b101

count() example:

1
2
3
4
5
6
7
aList = [123, 'xyz', 'zara', 'abc', 123];
print "Count for 123 : ", aList.count(123)
print "Count for zara : ", aList.count('zara')

# result:
Count for 123 : 2
Count for zara : 1