461. Hamming Distance

来源:互联网 发布:淘宝网连体长裤 编辑:程序博客网 时间:2024/06/14 05:03

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 ≤ 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.

class Solution {public:    int hammingDistance(int x, int y) {        int res = 0;        int a1[31] = {}; //确定长度时,就用数组;如果用地址代替,需要分配内存,容易出错!        int a2[31] = {};        for(int i = 0; i < 31; ++i) {            a1[i] = x%2;            x = x/2;            a2[i] = y%2;            y = y/2;            if(a1[i] != a2[i])                ++res;        }        return res;    }};

so easy~