Description
给定一个范围[a,b] (0<=a<b<=10^18) 求出该范围内二进制中1的个数最多的数,如果存在多个答案,输出最小的那个数
Input
输入数据有多组,每组数据输入两个整数a,b,表示区间[a, b]。
Output
输出该区间内二进制的1最多的整数,如果有多个数二进制1的个数相同,输出最小的那个数。
Sample Input
4 87 14
Sample Output
77
HINT
思路:
区间[a,b],如果a==b,输出a, 先把a,b化为二进制数,每位分别保存到数组中,如果a的二进制位数小于b的位数,那么直接输出 2^(b的位数-1) -1 ,也就是二进制数比b少一位且所有位均为1,如果a的位数等于b的位数,要求最小的符合题意的数,尝试着从a的二进制低位开始,如果是0,将其变为1,看是否小于等于b,如果是,继续操作,如果不是,退出。
代码:
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
#include <stdlib.h>
#include <cmath>
#include <iomanip>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <cctype>
using namespace std;
typedef long long ll;
ll a,b;
bool abit[65];
bool bbit[65];
ll two[65];
ll ans;
void pre()
{
two[0]=1;
for(int i=1;i<=64;i++)
two[i]=two[i-1]*2;
}
int cal(ll x,bool *bit)
{
int len=0;
while(x)
{
bit[len++]=x%2;
x/=2;
}
return len;
}
int main()
{
pre();
while(cin>>a>>b)
{
if(a>b)
swap(a,b);
if(a==b)
{
cout<<a<<endl;
continue;
}
int lena=cal(a,abit);
int lenb=cal(b,bbit);
if(lena<lenb)
{
ans=two[lenb-1]-1;
}
else
{
ans=a;
for(int i=0;i<lena;i++)
{
if(abit[i]==0)
{
ans+=two[i];
if(ans>b)
{
ans-=two[i];
break;
}
}
}
}
cout<<ans<<endl;
}
return 0;
}