Bit Mask 又是 位运算符的问题,每次都要死一次



In bit-wise expression, mask is a common term. You can get a certain bit-pattern using mask. For
example, if you want to make rst 4 bits of a 32-bit number zero, you can use 0xFFFFFFF0 as mask
and perform a bit-wise AND operation. Here you have to nd such a bit-mask.
Consider you are given a 32-bit unsigned integer N. You have to nd a mask M such that L
M U and N OR M is maximum. For example, if N is 100 and L = 50, U = 60 then M will be 59
and N OR M will be 127 which is maximum. If several value of M satis es the same criteria then you
have to print the minimum value of M.
Input
Each input starts with 3 unsigned integers N, L, U where L U. Input is terminated by EOF.
Output
For each input, print in a line the minimum value of M, which makes N OR M maximum.
Look, a brute force solution may not end within the time limit.


Sample Input


100 50 60
100 50 50
100 0 100
1 0 100
15 1 15
Sample Output


59
50
27
100
1

题意:就是让你求在给定的区间内【L,U】,让你求一个数N与区间内的数求或的最大值最后输出区间内的这个数。

思路:刚开始就简单的枚举一遍,TLE了,很无语,不知道如何下手,看来别人的博客,用位操作,首先4个字节32 位,就从31 位开始计算

AC 代码:

#include <iostream>
#include <cstdio>

using namespace  std;

int main(){
    int n,l,u;
    unsigned int m;
    while(~scanf("%d%d%d",&n,&l,&u)){
         m = 0;
        for(int i = 31;i >= 0;i--){
            if(m + (1 << i) <=u &&( (n & (1 << i) )  == 0||( m < l&& (l& (1<<i) )  ) ) ) {//这步不好理解首先要满足m不能比u大并且(满足n的二进制位和1 << i的各个位置上都有1或者当前数<l并且n的二进制位与1 << I 的二进制位上有相同的1)
                    m+=(1<<i);
            }
        }
        printf("%u\n",m);
    }
    return 0;
}


位操作就是坑,每次都会想不通,每日次都不长记性,要好好想想了

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值