Let's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integer x.
You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and is maximum possible. If there are multiple such numbers find the smallest of them.
The first line contains integer n — the number of queries (1 ≤ n ≤ 10000).
Each of the following n lines contain two integers li, ri — the arguments for the corresponding query (0 ≤ li ≤ ri ≤ 1018).
For each query print the answer in a separate line.
3 1 2 2 4 1 10
1 3 7
The binary representations of numbers from 1 to 10 are listed below:
110 = 12
210 = 102
310 = 112
410 = 1002
510 = 1012
610 = 1102
710 = 1112
810 = 10002
910 = 10012
1010 = 10102
题解:设L的二进制长度为len1,R的二进制长度为len2,分三种情况,①R的二进制全为1,直接输出r;②len2>len1且R的二进制不全为1,输出二进制长度为len2-1且二进制全为1的数;
③len2==len1,从高位到低位找到一个R的那一位是1,L的那一位是0的数位,再判断R在那一位之后是否全为1,如果是则把L的那一位之后且包括那一位全部变成1,如果不是则把
L的那一位之后的全部变成1,最后输出把L变成十进制再输出
#include<cstdio>
#include<queue>
#include<string.h>
#include<algorithm>
#include<stack>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define FIN freopen("in.txt","r",stdin)
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
int num1[66],num2[66];
int main(){
int n;
LL l,r;
// FIN;
scanf("%d",&n);
while(n--){
scanf("%I64d%I64d",&l,&r);
if(l==r) {printf("%I64d\n",r);continue;}
memset(num1,0,sizeof(num1));
memset(num2,0,sizeof(num2));
int len1=0,len2=0,cnt=0;
LL tmp=r;
while(l>0){
num1[len1++]=(l&1);
l>>=1;
}
while(r>0){
cnt+=(r&1);
num2[len2++]=(r&1);
r>>=1;
}
if(cnt==len2) printf("%I64d\n",tmp);
else if(len1<len2){
printf("%I64d\n",(1ll<<(len2-1))-1ll);
}
else{
int index=-1,flag=0;
LL ans=0;
for(int i=len1-1;i>=0;i--)
if(num1[i]==0&&num2[i]==1) {index=i;flag=1;break;}
cnt=0;
for(int i=index;i>=0;i--) if(num2[i]) cnt++;
if(cnt==index+1) for(int i=index;i>=0;i--) num1[i]=1;
else for(int i=index-1;i>=0;i--) num1[i]=1;
for(int i=0;i<len1;i++) if(num1[i]) ans+=(1ll<<i);
printf("%I64d\n",ans);
}
}
return 0;
}