HDU 最大的位或

最大的位或

Problem Description
B君和G君聊天的时候想到了如下的问题。
给定自然数l和r ,选取2个整数x,y满足l <= x <= y <= r ,使得x|y最大。
其中|表示按位或,即C、 C++、 Java中的|运算。
 

Input
包含至多10001组测试数据。
第一行有一个正整数,表示数据的组数。
接下来每一行表示一组数据,包含两个整数l,r。
保证 0 <= l <= r <=  1018
 

Output
对于每组数据输出一行,表示最大的位或。
 

Sample Input
 
  
51 100 11023 1024233 3221000000000000000000 1000000000000000000
 

Sample Output
 
  
15120475111000000000000000000
Problem Description
B君和G君聊天的时候想到了如下的问题。
给定自然数l和r ,选取2个整数x,y满足l <= x <= y <= r ,使得x|y最大。
其中|表示按位或,即C、 C++、 Java中的|运算。
 

Input
包含至多10001组测试数据。
第一行有一个正整数,表示数据的组数。
接下来每一行表示一组数据,包含两个整数l,r。
保证 0 <= l <= r <=  1018
 

Output
对于每组数据输出一行,表示最大的位或。
 

Sample Input
 
   
51 100 11023 1024233 3221000000000000000000 1000000000000000000
 

Sample Output
 
   
15120475111000000000000000000

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;
}

猜你喜欢

转载自blog.csdn.net/hh1258414454/article/details/80410632