题目:
存在多个y,使得给定的x满足:x+y==x|y
k指定多个y中的第几个
思路:
比如x=166,用二进制表示出来是101000
那么y用二进制表示出来第4位和第5位一定不能是1 即类似010111 (第4位和第5位必须是0)
#include <iostream>
#include <set>
#include <vector>
#include <assert.h>
using namespace std;
int solve(int x,int k)
{
assert(k);
vector<int> v;
vector<int>::iterator item;
int value = x;
int count = k;
int a = 1;
for (; value > 0; value = value >> 1)
{
if (((value & 0x1) == 0))
v.push_back(a);
a = a << 1;
}
v.push_back(a);
item = v.begin();
int result = 0;
bool IsInVector = true;
a = a << 1;
while (count){
if ((count & 1 )== 1){
if (item < v.end()){
result += *item;
}
else{
result += a;
IsInVector = false;
}
}
if (IsInVector == false || item >= v.end()){
a <<= 1;
}
else{
++item;
}
count >>= 1;
}
return result;
}
int main()
{
int x, k;
cin >> x;
cout << " ";
cin >> k;
cout<<solve(x,k)<<endl;
system("pause");
return 0;
}
转载于:https://blog.51cto.com/lingdandan/1833990