好未来笔试第二题
好未来第二题,最后9点0几调通了,结果回来一看结束了,说好的延长10分钟呢。。
题目:给定式子x y=x|y
输入x,k
输出满足式子的第k个y值。
大概思路:将k的二进制位依次次放到x为零的位置,然后与x异或得到结果。
我的想法是:假设y满足条件,那么y的二进制位上为1的地方,对应的x的位置一定是0;
求第k个满足条件的y,相当于把x为0的位置提取出来组成数字k。(二进制组成)
比如x=4 ,求第1个,就是把4(100)最后一个0提取出来,放进数字1,就得到101,然后101^100=1;
求第2个,就是把4(100)最后2个0提取出来,放进数字2(10),就得到110,然后110^100=2;
求第3个,就是把4(100)最后3个0提取出来,放进数字3(11),就得到111,然后111^100=3;
求第4个,就是把4(0100)最后3个0提取出来,放进数字4(100),就得到1100,然后1100^100=8;
。。。
那么求第k个,就直接把k按二进制的位数依次放到x为0的位置。再与x异或就得到了第k个满足条件的值。
#include <string>
#include <vector>
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <map>
using namespace std;
unsigned long long helper(unsigned long long x, unsigned long long k);
int main()
{
int T = 0;
cin >> T;
unsigned long long x = 0;
unsigned long long k = 0;
for (int i = 0; i < T; i )
{
cin >> x>>k;
cout<<helper(x, k)<<endl;
}
system("pause");
}
unsigned long long helper(unsigned long long x,unsigned long long k)
{
unsigned long long x1 = x;
unsigned long long x2 = x;
vector<int> data;
while (k)
{
int tmp = k & 1;
data.push_back(tmp);
k=k >> 1;
}
int count = 0;
int p =0;
while (true)
{
if ((x1 & 1) == 0)
{
unsigned long long tp = data[p];
if (tp == 1)
{
tp = tp << count;
x = x|tp;
}
p ;
if (p==data.size())break;
}
x1 = x1>>1;
count ;
}
unsigned long long res = x^x2;
return res;
}
#include <vector>
#include <iostream>
#include <unordered_map>
#include <algorithm>
#include <map>
using namespace std;
unsigned long long helper(unsigned long long x, unsigned long long k);
int main()
{
int T = 0;
cin >> T;
unsigned long long x = 0;
unsigned long long k = 0;
for (int i = 0; i < T; i )
{
cin >> x>>k;
cout<<helper(x, k)<<endl;
}
system("pause");
}
unsigned long long helper(unsigned long long x,unsigned long long k)
{
unsigned long long x1 = x;
unsigned long long x2 = x;
vector<int> data;
while (k)
{
int tmp = k & 1;
data.push_back(tmp);
k=k >> 1;
}
int count = 0;
int p =0;
while (true)
{
if ((x1 & 1) == 0)
{
unsigned long long tp = data[p];
if (tp == 1)
{
tp = tp << count;
x = x|tp;
}
p ;
if (p==data.size())break;
}
x1 = x1>>1;
count ;
}
unsigned long long res = x^x2;
return res;
}
难受。。最后没提交