461. Hamming Distance(转换成二进制比较)

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.

方法一:
class Solution {
    public int hammingDistance(int x, int y) {
         int [] Numx = new int[32];
         int [] Numy = new int[32];
         int t1=0;
         int t2=0;
           while(x>0){
              Numx[31-t1] = x%2;
              x = x/2;
              t1++;
           }
           while(y>0){
               Numy[31-t2] =y%2;
               y = y/2;
               t2++;
           }
        int total = 0;
        for(int i =0;i<32;i++){
            if(Numx[i]!=Numy[i]){
                total++;
            }      
        }
        return total;
    }
}

方法一:通过时间:14ms

思路:首先要理解数字是怎么转换成数组的
十进制转二进制(整数部分)
方法:用2辗转相除直到结果为1,将余数和最后的1从下向上的组合,就是我们想要的结果.
例如:60
60/2 = 30 余 0
30/2 = 15 余 0
15/2 = 7 余 1
7/2 = 3 余 1
3/2 = 1 余 1
1/2 = 0 余 1
所以十进制数60转为二进制数即为 111100
2)每个数转换成二进制的个数都不一样,所以规定一个length为32的数组,第一个数0在下标31中,第二个数0在下标30中,第三个数1在下标29中,以此类推。
3)记得先取余再除以2。
4)最后遍历两个长度为32的数组,每个比较就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值