461.ハミング距離(c++実現)
5741 ワード
問題の説明:
2つの整数間のハミング距離は、この2つの数字がバイナリビットの異なる位置に対応する数を指す.
2つの整数
注意:0≦
例:
2つの整数間のハミング距離は、この2つの数字がバイナリビットの異なる位置に対応する数を指す.
2つの整数
x
およびy
が与えられ、それらの間のハミング距離が計算される.注意:0≦
x
、y
<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)
{
a.push_back(0);
}
}
else
{
int aa=b.size();
for(int h=0;h)
{
b.push_back(0);
}
}
for(int kk=0;kk)
{
if(a[kk]+b[kk]==1)
count++;
}
}
return count;
}
};