C++ special number sum (enumeration)

Xiao Ming is very interested in the numbers containing 2, 0, 1, 9 in the digits (excluding leading 0). Such numbers from 1 to 40 include 1, 2, 9, 10 to 32, 39 and 40, a total of 28 , Their sum is 574.
Excuse me, in 1 to n, what is the sum of all such numbers?
The input format is
one line and contains an integer n.
The output format is
one line, containing an integer, which represents the sum of the numbers that meet the conditions.
Data range
1≤n≤10000
Input example:
40
Output example:
574

Since the data range of this question is very small, it is enough to perform regular enumeration and split numbers.

AC code:

#include<iostream>

using namespace std;

int n;
long long ans=0;

bool check(int x)
{
    
    
    int d=x,t;
    bool flag=false;
    while(d)
    {
    
    
        t=d%10;
        if(t==2||t==0||t==1||t==9)
        {
    
    
            flag=true;
            break;
        }
        d/=10;
    }
    return flag;
}

int main()
{
    
    
    cin>>n;
    for(int i=1;i<=n;++i)
        if(check(i)) ans+=i;
    cout<<ans;
    return 0;
}

Guess you like

Origin blog.csdn.net/qq_44643644/article/details/108855055