D - A or...or B Problem
Time limit : 2sec / Memory limit : 256MB
Score : 900 points
Problem Statement
Nukes has an integer that can be represented as the bitwise OR of one or more integers between A and B (inclusive). How many possible candidates of the value of Nukes's integer there are?
Constraints
- 1≤A≤B<260
- A and B are integers.
Input
The input is given from Standard Input in the following format:
A B
Output
Print the number of possible candidates of the value of Nukes's integer.
Sample Input 1
7 9
Sample Output 1
4
In this case, A=7 and B=9. There are four integers that can be represented as the bitwise OR of a non-empty subset of {7, 8, 9}: 7, 8, 9 and 15.
Sample Input 2
65 98
Sample Output 2
63
Sample Input 3
271828182845904523 314159265358979323
Sample Output 3
68833183630578410
思路:这题需要找出一个分界点,即找到最高位的B是1,A是0的位置x(最低位从0开始),那么对于所有OR的结果,x处要么是1要么是0,x是0有多少种呢?这里就需要从[A,1<<x)里挑选数进行OR,即有(1<<x)-A种,因为A到(1<<x)-1都可以表示出来;x处为1有几种呢?有两种情况①从(1<<x, B]里挑选,结果就不说了依此类推,②从上述两个区间都挑选,那就是也是(1<<x)-A种,然后上述两种两种情况可能会有重复,需要判断去重,最后判读是否要加上(1<<x)这一种就行了。
# include <bits/stdc++.h>
using namespace std;
typedef long long LL;
int main()
{
LL i, j, a, b, ans=0;
scanf("%lld%lld",&a,&b);
if(a == b)
return 0*puts("1");
for(i=60; i>=0; --i)
{
if((b>>i&1)^(a>>i&1))
break;
if(a>>i&1) a ^= 1LL<<i;
}
for(j=i-1; j>=0; --j)
if(b>>j&1)
{
ans += (1LL<<j+1)-1;
break;
}
ans += ((1LL<<i)-a)<<1;
if(j != -1 && a <= (1LL<<j+1)-1) ans -= (1LL<<j+1)-a;
printf("%lld\n",ans+(i!=0));
return 0;
}