【进制转换专题】牛记数

Description
一头奶牛在研究数字的表示法,它只会二进制数,在泥地上它用一个脚印表示0,而用它的脚来表示1. 显然,它最多能表示4个位置上的1.
现给定一个范围[s,t]  ( 1 <= s,t <= 15,000,000),请问这头牛可以表示其中的多少个数.

Input
* 只一行: 两个整数s 和t.
Output
* 只一行: 用少于4个1的二进制数可表示在[s,t]中的数的个数.
Sample Input
100 105
Sample Output
5
HINT
样例解释:
数    2进制数  1的个数 是否可表示
100  1100100   3       Yes
101  1100101   4       Yes
102  1100110   4       Yes
103  1100111   5       No
104  1101000   3       Yes
105  1101001   4       Yes

AC Code:

#include <iostream>
 
using namespace std;
 
int main()
{
    int s, e, i, j, c = 0, temp, x;
    bool flag;
     
    cin >> s >> e;
     
    for (i = s; i <= e; i++)
    {
        x = i;
        temp = 0;
        flag = true;
        for (j = 0; j < 32; j++)
        {
            temp += x & 1;
            if (temp == 5)
            {
                flag = false;
                break;
            }
            x >>= 1;
        }
        if (flag)
        {
            c++;
        }
    }
     
    cout << c << endl;
     
    return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/80244207