Let's denote as the number of bits set ('1' bits) in the binary representation of the non-negative integer x.
You are given multiple queries consisting of pairs of integers l and r. For each query, find the x, such that l ≤ x ≤ r, and is maximum possible. If there are multiple such numbers find the smallest of them.
The first line contains integer n — the number of queries (1 ≤ n ≤ 10000).
Each of the following n lines contain two integers li, ri — the arguments for the corresponding query (0 ≤ li ≤ ri ≤ 1018).
For each query print the answer in a separate line.
3 1 2 2 4 1 10
1 3 7
The binary representations of numbers from 1 to 10 are listed below:
110 = 12
210 = 102
310 = 112
410 = 1002
510 = 1012
610 = 1102
710 = 1112
810 = 10002
910 = 10012
1010 = 10102
题目链接:http://codeforces.com/problemset/problem/485/C
题目大意:给定一个区间[l, r],求这个区间里的数在转化为二进制的情况下,1的个数最多的数字;同时,当1的个数相同的时候,输出数最小的那个。
题目思路:先设置一个数组,用来存储1、10、100、1000这些二进制数,然后对这些数进行累加,直到大于等于r为止。此时的sum就是1的个数最多的那个数,但是有可能不在这个区间中,所以我们需要进行判断。假如他大于r的话,就减去最后相加的那个数,这样可以保证得出的结果是区间中1最多的但是数值最小的。
C++源代码如下:
#include <set>
#include <map>
#include <stack>
#include <cmath>
#include <queue>
#include <cstdio>
#include <string>
#include <vector>
#include <iomanip>
#include <cstring>
#include <iostream>
#include <algorithm>
#define For(i, n) for (int i = 1; i <= n; i++)
#define ForK(i, k, n) for (int i = k; i <= n; i++)
#define ForD(i, n) for (int i = n; i >= 0; i--)
#define Rep(i, n) for (int i = 0; i < n; i++)
#define RepD(i, n) for (int i = n; i >= 0; i--)
#define MemI(a) memset(a, 0, sizeof(a))
#define MemC(a) memset(a, '\0', sizeof(a))
#define PI acos(-1)
#define eps 1e-8
#define inf 0x3f3f3f3f
typedef long long ll;
using namespace std;
ll bit[65];
int main()
{
bit[0] = 1;
for (int i = 1; i <= 63; i++)
{
bit[i] = 2 * bit[i - 1];
}
int t;
ll l, r, sum;
scanf("%d", &t);
while (t--)
{
sum = 0;
scanf("%I64d%I64d", &l, &r);
int i;
for (i = 0; sum <= r; i++)
{
sum += bit[i];
}
i--;
while (sum > r)
{
sum -= bit[i];
if (sum < l)
sum += bit[i];
i--;
}
printf("%I64d\n", sum);
}
return 0;
}