1.源题目
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.
2.解决方法
方法1.暴力求解:依次对比两个数的二进制位,出现不同则加1
1.一个数A左移一位后再右移一位得到A0
2.比较A和A0,如果A和A0相等,则说明A的二进制数的最后一位为0,否则为1
1 | public class Solution{ |
方法2.通过二进制运算: 两个数异或后不同位为1,相同位的值为0,如x=1,y=4
x^y = (001)^(100) = (101)
n&(n-1)则可使最后一位1变为0,计算出1的个数,即为汉明距离,解法见下:
1 | public class Solution{ |
完整代码HammingDistance