Bits
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.
Input
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).
Output
For each query print the answer in a separate line.
题意为在[l,r]区间里找到一个最小的数,这个数的转化为二进制1的个数最多;
可以这样考虑,一个数 10010010 要找到比它小,但是二进制1多的数,可以贪心的把1变成0,然后把这个 1 后面的 0 变成 1 ;
例如变成:01111111,10001111,10010001;
最后判断一下就行,特别注意(1<<i)当i大于31时,也就是说当超过 int 型时,会爆,可以把1改为1ll;
代码:
#include<bits/stdc++.h>
#define ll long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
#define inf 0x3f3f3f3f
//ios::sync_with_stdio(false);
using namespace std;
const int N=100100;
const int M=1000100;
const ll mod=1e9+7;
vector<int>ve;//1的位置
void solve(ll p){
int cnt=0;
while(p){
cnt++;
if(p%2) ve.push_back(cnt);
p/=2;
}
}
int main(){
ios::sync_with_stdio(false);
int n;
cin>>n;
while(n--){
ve.clear();
ll l,r;
cin>>l>>r;
solve(r);
ll ans=r;//最小答案
int ms=ve.size();//1的个数
for(int i=ve.size()-1;i>=0;i--){
int b=ve[i]-1;
ll a=(1ll<<(ve[i]-1))-1;
for(int j=i+1;j<ve.size();j++){
a+=(1ll<<(ve[j]-1));
b++;
}
if(a>=l&&b>ms) ms=b,ans=a;
else if(a>=l&&b==ms&&a<ans) ans=a;
}
cout<<ans<<endl;
}
return 0;
}