Description
The cows, as you know, have no fingers or thumbs and thus are unable to play Scissors, Paper, Stone' (also known as 'Rock, Paper, Scissors', 'Ro, Sham, Bo', and a host of other names) in order to make arbitrary decisions such as who gets to be milked first. They can't even flip a coin because it's so hard to toss using hooves.
They have thus resorted to "round number" matching. The first cow picks an integer less than two billion. The second cow does the same. If the numbers are both "round numbers", the first cow wins,
otherwise the second cow wins.
A positive integer N is said to be a "round number" if the binary representation of N has as many or more zeroes than it has ones. For example, the integer 9, when written in binary form, is 1001. 1001 has two zeroes and two ones; thus, 9 is a round number. The integer 26 is 11010 in binary; since it has two zeroes and three ones, it is not a round number.
Obviously, it takes cows a while to convert numbers to binary, so the winner takes a while to determine. Bessie wants to cheat and thinks she can do that if she knows how many "round numbers" are in a given range.
Help her by writing a program that tells how many round numbers appear in the inclusive range given by the input (1 ≤ Start < Finish ≤ 2,000,000,000).
Input
Output
Sample Input
2 12
Sample Output
6
Source
#include<iostream>
using namespace std;
int c[33][33];
int bin[35]; //十进制n的二进制数
/*打表,计算nCm*/
void play_table(void) {
for (int i = 0; i <= 32; i++)
for (int j = 0; j <= i; j++)
if (!j || i == j)
c[i][j] = 1;
else
c[i][j] = c[i - 1][j - 1] + c[i - 1][j];
c[0][0] = 1;
return;
}
/*十进制n转换二进制,逆序存放到bin[]*/
int dec_to_bin(int n) {
int len = 0; //b[0]是二进制数的长度
while (n) {
bin[len++] = n % 2;
n /= 2;
}
return len;
}
/*计算比十进制数n小的所有RN数*/
int work(int n) {
int sum = 0; //比十进制数n小的所有RN数
dec_to_bin(n);
int len = dec_to_bin(n);
/*计算长度小于bin[0]的所有二进制数中RN的个数*/
for (int i = 1; i < len - 1; i++)
for (int j = i / 2 + 1; j <= i; j++)
sum += c[i][j];
/*计算长度等于bin[0]的所有二进制数中RN的个数*/
int zero = 0; //从高位向低位搜索过程中出现0的位的个数
for (int i = len - 2; i >= 0; i--)
if (bin[i]) //当前位为1
for (int j = (len + 1) / 2 - (zero + 1); j <= i; j++)
sum += c[i][j];
else
zero++;
return sum;
}
int main(void) {
play_table();
int start, finish;
cin >> start >> finish;
cout << work(finish + 1) - work(start) << endl;
return 0;
}