1. 程式人生 > >461.漢明距離(c++實現)

461.漢明距離(c++實現)

問題描述:

兩個整數之間的漢明距離指的是這兩個數字對應二進位制位不同的位置的數目。

給出兩個整數 x 和 y,計算它們之間的漢明距離。

注意:
0 ≤ xy < 231.

示例:

輸入: x = 1, y = 4

輸出: 2

解釋:
1   (0 0 0 1)
4   (0 1 0 0)
       ↑   ↑

上面的箭頭指出了對應二進位制位不同的位置。
實現方法:
class Solution {
public:
    int hammingDistance(int x, int y) {
        
int count=0; vector<int> a; vector<int> b; if(x==0&&y==0) return 0; else if(x==0&&y!=0) { while(y) { int temp=y%2; b.push_back(temp); y=y/2;
if(temp==1) count++; } } else if(x!=0&&y==0) { while(x) { int temp1=x%2; a.push_back(temp1); x=x/2; if(temp1==1) count++; } }
else { while(y) { int temp=y%2; b.push_back(temp); y=y/2; } while(x) { int temp1=x%2; a.push_back(temp1); x=x/2; } int jishu=max(a.size(),b.size()); if(jishu>a.size()) { int bb=a.size(); for(int hh=0;hh<jishu-bb;hh++) { a.push_back(0); } } else { int aa=b.size(); for(int h=0;h<jishu-aa;h++) { b.push_back(0); } } for(int kk=0;kk<jishu;kk++) { if(a[kk]+b[kk]==1) count++; } } return count; } };