nkoj 2060
Description
一个小女孩非常喜欢关于二进制位的问题,下面是其中一个问题:
给你两个整数L和R,找出a xor b结果值最大的一对,(l ≤ a ≤ b ≤ r)
xor表示异或,在c++里的运算符是"^"
Input
两个空格间隔的整数L和R (1<=l<=r<=1018)
Output
一个整数,表示最大的异或的结果
Sample Input
样例输入1:
1 2
样例输入2:
8 16
样例输入3:
1 1
Sample Output
样例输出1:
3
样例输出2:
31
样例输出3:
0
Hint
注意:一般情况下我们只在32位数字范围内进行位运算
如果要在64位也就是long long范围内做位运算,参与运算的必须是long long类型,比如把1左移60位,我们应写成“1LL<<60”
分析:
1 => 00001
2 => 00010
3 => 00011
4 => 00100
5 => 00101
6 => 00110
7 => 00111
8 => 01000
9 => 01001
10 => 01010
11 => 01011
12 => 01100
13 => 01101
14 => 01110
15 => 01111
16 => 10000
17 => 10001
18 => 10010
solve(l,r)表示区间[l,r]的最大异或。
由0~18可以归纳出,当l,r的二进制位数不同的时候,所求的就是 2^p-1 (其中p是r的二进制位数)
当l,r的二进制位数相同,根据异或运算的法则,最高位的计算结果一定是0,可以直接抹去。
代码如下:
#include<cstdio>
#include<iostream>
#define LL long long
using namespace std;
LL bitcnt(LL x){ //返回x的二进制位数
LL cnt=0;
while(x)cnt++,x>>=1;
return cnt;
}
LL solve(LL l,LL r){
LL a=bitcnt(l),b=bitcnt(r);
if(a!=b) return (1LL<<b)-1; //位数相同
LL ans= solve(l&((1LL<<(a-1))-1),r&(((1LL<<(b-1)))-1));
//位数不同,抹去最高位
return ans;
}
int main(){
LL a,b;
cin>>a>>b;
cout<<solve(a,b);
}
for循环版
#include<cstdio>
#include<iostream>
using namespace std;
int main(){
//freopen("123.in","r",stdin);
long long a,b,i,j,k,ans=0,temp;
bool flag=true;
cin>>a>>b;
if(a==b){
cout<<"0";
return 0;
}
for(i=62;i>=0;i--){
temp=1LL<<i;
if(temp>a&&temp<=b){
cout<<(temp^(temp-1));return 0;
}
if(temp<=a){
a=a-temp;
b=b-temp;
}
}
}