[leetcode]461. Hamming Distance
Analysis
待会要考政治—— [生死有命富贵在天!!!]
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.
把两个数转换成二进制,然后补零至位数相同,然后求海明威距离。
Implement
class Solution {
public:
int hammingDistance(int x, int y) {
vector<int> xx;
vector<int> yy;
while(x){
xx.push_back(x%2);
x /= 2;
}
while(y){
yy.push_back(y%2);
y /= 2;
}
int lenx = xx.size();
int leny = yy.size();
while(lenx < leny){
xx.push_back(0);
lenx++;
}
while(leny < lenx){
yy.push_back(0);
leny++;
}
int res = 0;
for(int i=0; i<lenx; i++){
if(xx[i] != yy[i])
res++;
}
return res;
}
};