https://leetcode.com/problems/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.
Note:
0 ≤ x
, y
< 231.
Example:
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.
Sol:
The hamming distance is the number of different digits of two numbers in binary digit.
Get every mod of x and y divided by 2, and add one to the answer when they are different.
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ # We can find the i-th bit (from the right) of a number by dividing by 2 i times, then taking the number mod 2. # Using this, lets compare each of the i-th bits, adding 1 to our answer when they are different. ans = 0 while x or y: ans += ( x%2 ) ^ ( y%2 ) x /= 2 y /= 2 return ans
Note:
1 x ^ y, where ^ means exclusive or.
return 1 only when two bits are different.
1 0 ==> 1
0 1 ==> 1
0 0 ==> 0
1 1 ==> 0
2 x & y, where & means and.
return 1 only when two bits are 1.
1 1 ==> 1
1 0 ==> 0
0 1 ==> 0
0 0 ==> 0
3 This problem is clearly about bit manipulation. Think of bit operators.
4 The end condition of division is the last dividend goes down to zero.