Problem A | 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 Msatisfies 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 |
Member of Elite Problemsetters' Panel
#include <iostream>
#include <cstdio>
using namespace std;
long long N, L, R, b[64];
int a[64];
void init_arr() {
b[0] = 1;
for (int i = 1; i <= 32; i ++) {
b[i] = b[i - 1] * 2;
}
}
void solve() {
for (int i = 0; i < 32; i ++) {
a[i] = N % 2;
N /= 2;
}
long long x, y, ans = 0;
for (int i = 31; i >= 0; i --) {
if(a[i] == 0) {
x = ans + b[i];
y = ans + b[i + 1] - 1;
if (x <= R && y >= L) {
ans += b[i];
}
} else {
x = ans;
y = ans + b[i] - 1;
if (y < L) {
ans += b[i];
}
}
}
printf("%lld\n", ans);
}
int main() {
init_arr();
while (scanf("%lld%lld%lld", &N, &L, &R) == 3) {
solve();
}
return 0;
}