LeetCode: 461. Hamming Distance

来源:互联网 发布:淘宝免费注册流程 编辑:程序博客网 时间:2024/06/17 00:31

题目名称:

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.


题目解释:

给定两个整数x、y ,其中 0 ≤ x, y < 2^31, x、y的海明距离定义为两个整数二进制位上不同数的个数。
例如:
x = 1, y = 4
4 3 2 1
x = 0 0 0 1
y = 0 1 0 0
x、y在第三位和第一位上的二进制数不一致,所以整数1、4之间的海明距离为: 2。


解题方案:

既然是判断整数的二进制位上标识是否相等,那么我们可以先把整数从十进制数转换为二进制数,然后判断两个整数每一个对应二进制位的数值是否相等。十进制转化二进制的方法为:使用连续除2取余,将余数倒叙排列即可。
例如整数 5:
5 / 2 = 2—–1
2 / 2 = 1—–0
1 / 2 = 0—–1
5 => 101
由十进制转换二进制的过程可知,我们直接在进制转换的过程中两整数二进制位即可,直到最大的整数除尽。


AC代码:

class Solution {public:    int hammingDistance(int x, int y) {      int count = 0;      while (x != 0 || y != 0) {        int xbit = x % 2;        int ybit = y % 2;        if(xbit != ybit) {          count++;        }        x /= 2;        y /= 2;      }      return count;    }};
0 0
原创粉丝点击