题目:
Problem - 276D - Codeforces
思路:
l <= r
1. l == r ,异或的结果为0
2. l < r
(注意:二进制位中,某一位是1,这一位后面的全是1,也没这个1大,比如1000 > 0111)
r比l大,我们找到第一个不同的位置,这个位置一定是r是1,l是0 (因为r>l).
(前面的位置都不用考虑了,无法操作到。)
此时 r 这一位开始,最小也是10000 ,而 l 从这一位开始,最大也是01111。
r或许更大,l或许更小,不过这两个值是绝对在范围内的,而且也只差1.
他们异或就是最大值11111
代码:
void solve()
{
int l,r;
cin >> l >> r;
if (l == r)
{
cout << 0;
return;
}
int fd = 0;
for (int i = 60; i >= 0; i--)
{
bool pl = l & (1ll << i);
bool pr = r & (1ll << i);
if (pl != pr)
{
fd = i; break;
}
}
cout << (1ll << (fd+1)) - 1;
}
signed main()
{
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int t = 1;
//cin >> t;
while (t--)
{
solve();
}
return 0;
}