原题链接:https://vjudge.net/problem/CodeForces-611B
The year 2015 is almost over.
Limak is a little polar bear. He has recently learnt about the binary system. He noticed that the passing year has exactly one zero in its representation in the binary system — 201510 = 111110111112. Note that he doesn't care about the number of zeros in the decimal representation.
Limak chose some interval of years. He is going to count all years from this interval that have exactly one zero in the binary representation. Can you do it faster?
Assume that all positive integers are always written without leading zeros.
Input
The only line of the input contains two integers a and b (1 ≤ a ≤ b ≤ 1018) — the first year and the last year in Limak's interval respectively.
Output
Print one integer – the number of years Limak will count in his chosen interval.
Examples
Input
5 10
Output
2
Input
2015 2015
Output
1
Input
100 105
Output
0
Input
72057594000000000 72057595000000000
Output
26
Note
In the first sample Limak's interval contains numbers 510 = 1012, 610 = 1102, 710 = 1112, 810 = 10002, 910 = 10012 and 1010 = 10102. Two of them (1012 and 1102) have the described property.
我的理解:
题目本身比较好理解,就是从给定的两个数的区间中,找出他们的二进制数中含有0的个数只有一个的总数。
本来我想着用数组做,但奈何存不下,只能过前三个样例,数一大就不行了,于是看了别人的题解才想到原来可以这么简单,不只暴力求解,递归搜索就可以。。
思路:让找二进制中0的个数只有一个的,因此从1开始找。1*2 = 2;2对应的二进制就是10,就符合要求。因为10(也就是2)符合,而10<<1(10左移一位)变成了100,不符合,所以原来的数1*2+1即可寻找下一个数也就是3.而3对应的二进制是11,不符合,不符合的话3*2=6,6对应的二进制是110,符合。
综上所述,对于一个二进制数,如果不符合规律,乘以2一定符合,如果符合的话,继续向下找即可,而向下找则需这个数*2+1。话不多说,上AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
long long a, b, ans;
void dfs(long long x, int flag)
{
if(x>b)//相当于a比b都大,直接退出
return ;
if(x >= a && x <= b && flag == 1)
ans++;
if(!flag)//flag为0,说明2*x+1符合
{
dfs(2*x, 1);
dfs(2*x+1, 0);
}
else//说明flag等于1,既2*x合适,此时就可继续向下找,因为2*x合适,所以向下找+1即可。
dfs(2*x+1,1);
}
int main()
{
scanf("%lld%lld", &a, &b);
ans = 0;
dfs(1,0);
printf("%lld\n", ans);
return 0;
}