Binary system(求区间内二进制中1的个数最多的数)

16 篇文章 0 订阅
5 篇文章 0 订阅

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


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值