UVALive 6918 And Or(位运算)

题目地址 :https://icpcarchive.ecs.baylor.edu/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4930
位运算的一道题。
A |(A+1)|(A+2)|…..B 的最终值为A和B二进制位从高到低遇到第一个不相同的位时,后面全部取1的二进制所得的值。同理 A&(A+1)&(A+2)&………B的最终值为后面全部取0所得二进制转化为十进制的值。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <vector>

using namespace std;

int main()
{
    int n;
    int kase = 0;
    scanf("%d", &n);
    while(n--)
    {
        long long int x, y;
        scanf("%lld %lld", &x, &y);
        long long int tmp1;
        tmp1 =  1l;
        tmp1 <<= 62;
        while(((tmp1 & x) == (tmp1 & y)) && tmp1)//从long long int 最高位开始, 判断x, y的每一位二进制位是否相同, 不相同时退出循环
        {
            tmp1 >>= 1;
        }
        long long int _and = 0;
        long long int _or = 0;
        while(tmp1)//从不同的二进制位开始,tmp1的全部位取1, 然后与y按位或即可得到第一个答案
        {
            _or |= tmp1;
            tmp1 >>= 1;
        }
        long long int ans1 = (y | _or);
        _and = ~_or;//全部取反,与y按位与得到第二个答案
        long long int ans2 = (x & _and);
        printf("Case %d: %lld %lld\n", ++kase, ans1, ans2);
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值