码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-461. Hamming Distance

时间:2017-01-20 10:58:16      阅读:142      评论:0      收藏:0      [点我收藏+]

标签:pos   amp   pre   bit   which   diff   不同   res   its   

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.

思路:算两个数二进制按位比较不同位的个数,先异或,再求xor的二进制1的个数。

public class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y;
        int distance = 0;
        while (xor != 0) {
            distance ++;
            xor &= (xor-1); //清除xor最右边的1
        }
        return distance;
    }
}

 

LeetCode-461. Hamming Distance

标签:pos   amp   pre   bit   which   diff   不同   res   its   

原文地址:http://www.cnblogs.com/wxisme/p/6322089.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!