New Year and Old Property
Time Limit:2000MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u
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.
Sample Input
Input
5 10
Output
2
Input
2015 2015
Output
1
Input
100 105
Output
0
Input
72057594000000000 72057595000000000
Output
26
Hint
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.
题意:
输出给定范围的数中,对应二进制只有一个零的数的个数
例如范围是5~10,则有两个数的二进制中只有一个零(5和6);
做法:
由于只有一个零的二进制数是这样的:
2: 10
5: 101
6: 110
11: 1011
13: 1101
14: 1110
23: 10111
27: 11011
29: 11101
30: 11110
47: 101111
55: 110111
59: 111011
61: 111101
62: 111110
所以打表记录每个数的值,然后再遍历一遍范围内有多少个数;
1到2的64次方内总共有(1+63)*63/2=2016个(好巧。。。。)
咦,有符号不是到2的63次方减一吗。。。数组开大点没关系。。。
代码如下:
#include <iostream>
#include <string.h>
const int maxn = 2080 + 100;
using namespace std;
long long low, high, jiafa, arr[maxn];
void solu()
{
jiafa=0;
for(int i=1; i<64; i++){
for(int j=0; j<i; j++){
long long temp=0;
for(int k=0; k<=i; k++){
if(k!=j)
temp += (long long)1<<k; //由二进制定义求十进制数
}
arr[jiafa++]=temp;
}
}
}
int main()
{
solu();
int cnt;
while(cin>>low>>high){
cnt = 0;
for(int i=0;i<jiafa;i++){
if(arr[i]>=low&&arr[i]<=high)
cnt++;
}
cout<<cnt<<endl;
}
return 0;
}