LeetCode——461. Hamming Distance(C++,模拟)

来源:互联网 发布:徐老师淘宝店叫什么 编辑:程序博客网 时间:2024/06/05 17:55

题目链接

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.

Note:
0 ≤ xy < 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.
题解:
逐位比较。
class Solution {public:    int hammingDistance(int x, int y) {        int res=0;        int maxv=x>y?x:y;        int minv=x-maxv+y;        while(maxv)        {            if(maxv%2!=minv%2)                res++;            maxv/=2;            minv/=2;        }        return res;    }};
原创粉丝点击