Little Girl and Maximum XOR
64-bit integer IO format: %I64d Java class name: Any
A little girl loves problems on bitwise operations very much. Here's one of them.
You are given two integers l and r. Let's consider the values of for all pairs of integers a and b (l ≤ a ≤ b ≤ r). Your task is to find the maximum value among all considered ones.
Expression means applying bitwise excluding or operation to integers x and y. The given operation exists in all modern programming languages, for example, in languages C++ and Java it is represented as "^", in Pascal — as «xor».
Input
The single line contains space-separated integers l and r (1 ≤ l ≤ r ≤ 1018).
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Output
In a single line print a single integer — the maximum value of for all pairs of integers a, b (l ≤ a ≤ b ≤ r).
Sample Input
1 2
3
8 16
31
1 1
0
1 /* 2 2016年4月22日00:05:10 3 ^ 为异或运算 4 经过打表可得规律答案要么是0 要么是2的N次 - 1 5 6 要得到最大的XOR值,其值一定是2的N次 - 1 7 8 即在l 和 r的二进制中,从左到右遍历过去如果碰到 (2 ^ i)&l 为 1 , (2 ^ i)&r 为 0 9 即在 l 和 r 之间一定存在 形如 011111111 和 100000000 这样的数。 10 11 则可说明在[l , r]中存在 011111111111 和 10000000000 可得到最大XOR值为2的N次 - 1 12 13 PS:不会存在首先出现 l 为 0 r 为 1 的情况,因为 l < r 14 */ 15 16 # include <iostream> 17 # include <cstdio> 18 # include <cstring> 19 # include <algorithm> 20 # include <queue> 21 # include <vector> 22 # include <cmath> 23 # define INF 0x3f3f3f3f 24 using namespace std; 25 26 int main(void) 27 { 28 int i; 29 long long l, r, ans; 30 while (cin>>l>>r){ 31 // 1<<i 相当于 2的i次方 32 // 1000 0000 0 第9位 2的8次方 1<<8 33 // 所以第64位 2的63次方 即 1<<63 34 for (i = 63; i >= 0; i--){ 35 if ((l&(1LL<<i)) ^ (r&(1LL<<i))){ // 1为int类型 要转为LL 36 break; 37 } 38 } 39 ans = (1LL<<(i+1)) - 1; // 要在原来位数上加一位 然后减1 40 cout<<ans<<endl; 41 } 42 43 return 0; 44 }