Leetcode 461(Java)

来源:互联网 发布:win7局域网网络图标 编辑:程序博客网 时间:2024/06/13 14:10

今天长春的天气很好阿,解题思路都跟着比较清晰嘻嘻。先贴上题目: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.

要比较每一位的差别脑子里第一个蹦出来的就是按位来做运算,用0来按位或不好实现左右移,那么就用一个1来按位与。开辟一个新变量,首先将1放在最低位,与输入的x,y按位与,比较结果即可知道x,y的最低位是否相同,接下来把这个1往左移动,就可以继续比较x,y的更高位数啦,AC代码如下:
public class Solution {
public int hammingDistance(int x, int y) {
int num = 0;
for(int i=0;i<32;i++){
int compare=1<<i;
if((compare&x)!=(compare&y)){
num++;
}
}
return num;
}
}

0 0
原创粉丝点击