Round Numbers
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, 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
Line 1: Two space-separated integers, respectively
Start and
Finish.
Output
Line 1: A single integer that is the count of round numbers in the inclusive range
Start..
Finish
Sample Input 2 12 Sample Output 6 Source |
题目大意:
已知两个数 a b ,求在 a 和 b 之间二进制数中 0 的个数大于 1 的个数的数的个数。。。(语文表达不行。。)
思路:
第一步,计算二进制长度小于finish的个数,(最高位肯定为1)
第二步,处理二进制长度和finish相同的情况
注: c 数组是储存组合数的,计算原理为
#include <iostream>
#include <cstring>
using namespace std;
int c[40][40];
void init() //初始化
{
for( int i = 0;i <= 35;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];
}
}
}
int dell(int a)
{
int st[40];
int i, j;
for( i = 0;a!=0;i++ )
{
st[i] = a%2;
a /= 2;
}
int len = i - 1;
int sum = 0;
for( i = 1;i < len;i++ )
{
for( j = i/2+1 ;j <= i;j++ )
{
sum += c[i][j];
}
}
int zero = 0;
for( i = len;i >= 1;i-- )
{
if( st[i-1]==1 )
for( j = len/2-zero;j < i;j++ )
sum += c[i-1][j];
else
zero++;
}
return sum;
}
int main()
{
init();
int a, b;
cin>>a>>b;
cout<<dell(b+1)-dell(a)<<endl; //算法不包含 数 本身, 所以 b 要 加一
return 0;
}