C++硬解,位运算的一个题目
class Solution {
public:
int minimizeXor(int num1, int num2) {
//把num1转换为2进制字符串,从低位到高位,统计1的个数
string s1 = "";
int c1 = 0;
while(num1)
{
if(num1 % 2 == 1)
{
s1 += '1';
c1++;
}
else
s1 += '0';
num1 /= 2;
}
//把num2转换为2进制字符串,从低位到高位,统计1的个数
string s2 = "";
int c2 = 0;
while(num2)
{
if(num2 % 2 == 1)
{
s2 += '1';
c2++;
}
else
s2 += '0';
num2 /= 2;
}
//结果的二进制字符串,这里要注意字符串s长度应为s1和s2中最大的长度
string s = "";
int size = s1.size();
if(s2.size() > s1.size())
size = s2.size();
for(int i = 0; i < size; i++)
{
if(i < s1.size() && s1[i] == '1')
s += '1';
else
s += '0';
}
//如果s1中1多
if(c1 > c2)
{
int c = c1 - c2;
for(int i = 0; i < s.size(); i++)
{
if(s[i] == '1')
{
s[i] = '0';
c--;
if(c == 0)
break;
}
}
}
else if(c1 < c2) //如果s2中1多
{
int c = c2 - c1;
for(int i = 0; i < s.size(); i++)
{
if(s[i] == '0')
{
s[i] = '1';
c--;
if(c == 0)
break;
}
}
}
int res = 0;
int p = 0;
for(int i = 0; i < s.size(); i++)
{
if(i == 0)
p = 1;
else
p *= 2;
if(s[i] == '1')
res += p;
}
return res;
}
};