The Hamming distancebetween two integers is the number of positions at which the corresponding bitsare different.
Given two integers xand 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 arrowspoint to positions where the corresponding bits are different.
谷歌翻译:两个整数之间的汉明距离是相应位不同的位置的数目。给定两个整数x和y,计算汉明距离。
这个题目的意思是,输入两个整数,看这两个整数对应的二进制位有哪些不一样。
Java的Unicode编码中,一个字符代表两个字节,32bit。可以用异或运算符,这个在以后的LeetCode当中运用的很多,所以多练习一下就会好了。异或是逻辑运算符。Java中逻辑与'&&'(),逻辑或'||',逻辑非'!',逻辑异或'^',逻辑与'&',逻辑或'|'。逻辑&&和&具有相同的功能,两边同时为true,则结果为true。但是对于&&,已知左边为false,则不计算后面的表达式,因为结果已经确定了为false;逻辑||和'|',两边同时为false,则结果为false。否则有一个为true,则结果为true。但是对于||,当左边有一个为true,则不计算后面的表达式。异或记住"同0异1",相同位是0,不同则为1。代码如下:
public class Solution{
public int hammingDistance(int x, int y) {
int temp=x^y;//^在word中复制过来,两个整数异或,然后数一的个数
int dis=0;
while (temp != 0) {
if ((temp >> 1)<< 1 != temp) { // temp右移一左移动一位,相当于最后一位设为0;如果等于原数,就证明原来最后一位就是0.这个比较巧妙,也可以将这个数变为二进制,然后存储在集合中,遍历其中1的个数
++dis;
}
temp >>= 1;
}
return dis;
}
}