461. Hamming Distance

来源:互联网 发布:单片机延时1s程序 编辑:程序博客网 时间:2024/06/08 01:35

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 ≤ xy < 231.

Example:

Input: x = 1, y = 4Output: 2Explanation:1   (0 0 0 1)4   (0 1 0 0)       ↑   ↑The above arrows point to positions where the corresponding bits are different.
Code:

public class Solution {    public int hammingDistance(int x, int y) {        int z=0;                int a=x^y;        String b=Integer.toBinaryString(a);       char[] bbb=b.toCharArray();        for(int i=0;i<bbb.length;i++){                if('1'==bbb[i])        z=z+1;        }        return z;    }}



思路是把x和y两个整数异或运算,然后讲结果转为二进制,二进制然后转化为char[]数组。进行遍历,时间复杂度是O[n]。

第一遍提交的时候遇到的问题是 画蛇添足地先把x、y转为二进制,然后转回int类型进行异或。但是二进制的是字符串 很长,再转回去导致溢出。所以failed。

XOR也就是异或 英文为exclusive OR。


第二种:

        String b=Integer.toBinaryString(x^y);        b=b.replaceAll("0","");        return b.length();

但是运算时间更慢了。-= =

同时,发现不管什么进制,进行异或的时候都是二进制来异或然后显示成这个。

以及文中答案中的一个新的方法:

 Integer.bitCount(x ^ y);
一行就可以完美解决本问题。


0 0
原创粉丝点击