字节跳动2017客户端工程师实习生笔试题-第四题

时间限制:C/C++ 1秒,其他语言2秒

空间限制:C/C++ 32M,其他语言64M

给定 x, k ,求满足 x + y = x | y 的第 k 小的正整数 y 。 | 是二进制的或(or)运算,例如 3 | 5 = 7。

比如当 x=5,k=1时返回 2,因为5+1=6 不等于 5|1=5,而 5+2=7 等于 5 | 2 = 7。

每组测试用例仅包含一组数据,每组数据为两个正整数 x , k。 满足 0 < x , k ≤ 2,000,000,000。

输出一个数y。

example:

input:  5  1 

output: 2

 1 /*学自csdn题解*/
 2 #include<iostream>
 3 #include<cstdio>
 4 using namespace std;
 5  
 6 long long theNum(int x, int k)
 7 {
 8     long long tmp = x;
 9     long long index1 = 1;
10     long long index2 = 1;
11     //当index2小于等于k时,进入循环
12     while (index2 <= k)
13     {
14         //(index1 & tmp)== 0  代表找到tmp二进制中为0的一位;
15         //若 y与 x的二进制位互反,即(index1 & tmp)== 0,则x+y==x|y;
16         if ((index1 & tmp) == 0)
17         {
18             //设x的二进制在第i位为0 ,则y二进制的第i位就有0、1两种取法,故index2<<=1;
19             if (index2 & k)
20             {
21                 //如果k对应的位是1,则tmp 更新为tmp = tmp | index1。why?
22                 //因为,index2 & k 意味着在此处k%2==1,则要把index1加给tmp;
23                 tmp = tmp | index1;
24             }
25             index2 <<= 1;//index2向左移动一位
26         }
27         //index1向左移动一位
28         index1 <<= 1;
29     }
30     return (tmp - x);
31 }
32  
33 int main(void)
34 {
35     int x, k;
36     while (cin >> x >> k)
37     {
38         cout << theNum(x, k) << endl;
39     }
40     return 0;
41 }
原文地址:https://www.cnblogs.com/Amaris-diana/p/13226520.html