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
10Input: 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 | class Solution(object): |
Python
bin() example:1
2
3
4
5number = 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
7aList = [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