本文共 928 字,大约阅读时间需要 3 分钟。
题目:
The 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 = 4Output: 2Explanation:1 (0 0 0 1)4 (0 1 0 0) ↑ ↑The above arrows point to positions where the corresponding bits are different.思路:
求两个数的汉明距离,用取余方法,算出x的二进制表示结果,若不到32位,则补0。并按位比较x与y
代码:
class Solution {public: int hammingDistance(int x, int y) { vector x1, y1; int count = 0; int count_x = 0; int count_y = 0; while (x>0){//用取余方法,算出x的二进制表示结果 x1.push_back(x % 2); x = x / 2; count_x++; } while (count_x<31){//若不到32位,则补0 x1.push_back(0); count_x++; } while (y>0){//与x同样 y1.push_back(y % 2); y = y / 2; count_y++; } while (count_y < 31){ y1.push_back(0); count_y++; } for (int i = 0; i != 31; i++){ if (x1[i] ^ y1[i]){//按位比较x与y的 count++; } } return count; }};
转载地址:http://cnmii.baihongyu.com/