最大的位或
给定自然数l和r ,选取2个整数x,y满足l <= x <= y <= r ,使得x|y最大。
其中|表示按位或,即C、 C++、 Java中的|运算。
第一行有一个正整数,表示数据的组数。
接下来每一行表示一组数据,包含两个整数l,r。
保证 0 <= l <= r <= 1018。
给定自然数l和r ,选取2个整数x,y满足l <= x <= y <= r ,使得x|y最大。
其中|表示按位或,即C、 C++、 Java中的|运算。
第一行有一个正整数,表示数据的组数。
接下来每一行表示一组数据,包含两个整数l,r。
保证 0 <= l <= r <= 1018。
1:1
10:0 1 0 1 0
最大的位或:15:11111
10 11
10:0 1 0 1 0
11:0 1 0 1 1
最大的位或:0 1 0 1 1
如果头两位相同,并且都为1 sum+=(long long)pow(2,当前位)
否则,sum+=(long long)pow(2,当前位+1)-1 结束
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
int p1[100],p2[100];
long long int a,b;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%lld%lld",&a,&b);
if(a==b)
printf("%lld\n",a);
else
{
memset(p1,0,sizeof(p1));
memset(p2,0,sizeof(p2));
int i=0,j=0;
while(a!=0)
{
int t=a%2;
p1[i++]=t;
a/=2;
}
while(b!=0)
{
int t=b%2;
p2[j++]=t;
b/=2;
}
int k=max(i,j);
long long sum=0;
for(int r=k-1;r>=0;r--)
{
if(p1[r]==p2[r])
{
if(p1[r]==1)
{
sum+=(long long)pow(2,r);
}
}
else
{
sum+=(long long)pow(2,r+1)-1;
break;
}
}
printf("%lld\n",sum);
}
}
return 0;
}