LeetCode-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.
思路:算两个数二进制按位比较不同位的个数,先异或,再求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; } }
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。