Bit Mask | |
Time Limit | 1 Second |
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 first 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 find such a bit-mask.
Consider you are given a 32-bit unsigned integer N. You have to find 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 satisfies 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 | Output for Sample Input |
100 50 60 | 59 |
解决方案:完全想不不出来啊,看来还是要多练。。。。。既然他是32位的无符号数字,可以把它分解成二进制,存入数组中,然后逐位枚举。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
long long N,L,R;
int BitN[33];
int result[33];
long long S;
long long p(long long i){
long long sum=1;
for(long long j=1;j<i;j++){
sum*=2;
}
return sum;
}
long long Sum(){
long long sum=0;
for(long long i=1;i<=32;i++){
sum+=result[i]*p(i);
}
return sum;
}
int main(){
while(~scanf("%I64d%I64d%I64d",&N,&L,&R)){
S=1;
long long NN=N;
memset(result,0,sizeof(result));
for(long long i=1;i<=32;i++){
BitN[i]=NN&S;
NN>>=(1);
}
for(long long i=32;i>=1;i--){
if(BitN[i]==0){
result[i]=1;
if(Sum()>R){
result[i]=0;
}
else result[i]=1;
}
else {
long long temp=Sum();
long long x=temp;
long long y=temp+p(i)-1;///通过对该位的所有后面的位都置1来判断
if(y<L)///若该位的所有后面的位都置1所得的结果比L小,那么此位必须是1
result[i]=1;
}///判断该位上是0还是1,有时候1是必须的,应为这个不为1,那么得到的结果永远不会在L之上。
}
cout<<Sum()<<endl;
}
return 0;
}