本文主要是介绍力扣-461.汉明距离,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Method 1
直接比较x,y二进制中的每一位,如果不同则cnt加一,并且x,y每次右移一位
class Solution {
public:int hammingDistance(int x, int y) {int cnt = 0;while(x > 0 && y > 0) {if((x & 1) != (y & 1)) cnt++;x >>= 1;y >>= 1;}while(x > 0) {if(x & 1) cnt++;x >>= 1;}while(y > 0) {if(y & 1) cnt++;y >>= 1;}return cnt;}
};
Method 2
使用异或运算,当二进制位相同时为1,不同时为0
class Solution {
public:int hammingDistance(int x, int y) {int cnt = 0;int s = x ^ y;while(s > 0) {cnt += s & 1;s >>= 1;}return cnt;}
};
这篇关于力扣-461.汉明距离的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!