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
1.若l == r 或者r == 2 ^ n - 1则直接输出r
2.把l和r化为二进制存在数组s1, s2里,从高位开始遍历s2数组,若存在s2[i] == 1 && s1[i] == 0,此时判断s2中0..i-1是否全为一,若全为1则直接俄输出s2,若不全为1,则把s2[i] = 0, 并且把s2中1..i-1变为1在算出s2输出.
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
typedef long long ll;
int s1[100], s2[100];
int solve(ll p, int *s){
int k = 0;
while(p){
s[k++] = p % 2;
p /= 2;
}
return k;
}
int main(){
// freopen("in.txt", "r", stdin);
int n;
scanf("%d", &n);
while(n--){
memset(s1, 0, sizeof(s1));
memset(s2, 0, sizeof(s2));
ll l, r;
scanf("%I64d%I64d", &l, &r);
if(l == r){
printf("%I64d\n", r);
continue;
}
int sign = 0;
int len1 = solve(l, s1);
int len2 = solve(r, s2);
for(int i = 0; i < len2; i++){
if(s2[i] == 0){
sign = 1;
break;
}
}
if(sign == 0){
printf("%I64d\n", r);
continue;
}
for(int i = len2 - 1; i >= 0; i--){
if(s2[i] == 1 && s1[i] == 0){
sign = 0;
for(int k = i-1; k >= 0; k--)
if(s2[k] == 0){
sign = 1;
break;
}
if(sign == 0)
break;
for(int j = i-1; j >= 0; j--)
s2[j] = 1;
s2[i] = 0;
break;
}
}
ll p = 0;
for(int i = len2 - 1; i >= 0; i--){
p = p * 2 + s2[i];
}
printf("%I64d\n", p);
}
return 0;
}