区间或和(2019牛客寒假算法基础集训营 Day6-G)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011815404/article/details/88382580

【题目描述】

求a|(a+1)|(a+2)|...|(b-1)|b。

其中|表示按位或

【输入描述】

多组输入,每行两个数表示a和b

【输出描述】

对于每组输入,输出一个数a|(a+1)|(a+2)|...|(b-1)|b。

【样例】

示例1

输入
99 109
68 77
55 66
34 43
1111234 1114321
输出
111
79
127
47
1179647

思路:

对于异或操作,只有当两个数相同时才为 0,将 a、b 化为二进制异或一遍可发现:每 2^(i-1) 个数可以将第 i 位从 0 变为 1,因此若 a 的二进制数的位数小于 b 时,就将 a 与 a+1 相或

【源代码】

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#define PI acos(-1.0)
#define E 1e-9
#define INF 0x3f3f3f3f
#define LL long long
const int MOD=1E9+7;
const int N=5000000+5;
const int dx[]= {-1,1,0,0};
const int dy[]= {0,0,-1,1};
using namespace std;

int main(){
    LL a,b;
    while(scanf("%lld%lld",&a,&b)!=EOF){
        while(a<b)
            a=a|(a+1);
        printf("%lld\n",a);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/u011815404/article/details/88382580
今日推荐