其他分享
首页 > 其他分享> > 计算小于等于n的幸运数有多少个

计算小于等于n的幸运数有多少个

作者:互联网

#include <iostream>
using namespace std;

int f(int x)
{
    int sum = 0;
    while (x > 0)
    {
        sum += x % 10;
        x = x / 10;
    }
    return sum;
}

int g(int x)
{
    int sum = 0;
    while (x > 0)
    {
        sum += x % 2;
        x = x / 2;
    }
    return sum;
}

int count_lucky_number(int n)          //计算小于等于n的幸运数个数
{
    int count, x;
    count = 0;
    for (x = 1; x <= n; x++)
    {
        if (f(x) == g(x))
            count++;
    }
    return count;
}

int main(void)
{
    int n;
    cin >> n;
    cout << count_lucky_number(n) << endl;
    return 0;
}

 

标签:count,小于,return,10,int,sum,while,幸运,数有
来源: https://blog.csdn.net/amocken/article/details/117826747