Digital and [Blue Bridge Cup 2017 Finals]

Topic link: Digital and
time limit: 1 Sec Memory limit: 256 MB

Title description:
Mathematician Gauss was very talented when he was very young. The arithmetic topic designated by the teacher once is: 1+2+…+100.
Gauss immediately answered: 5050!
Your mission is similar this time. But it is not adding up the numbers one by one, but adding up each digit of the number. So the "sum" from 1 to 100 is: 901
from 10 to 15 is: 21, that is: 1+0+1+1+1+2+1+3+1+4+1+5, this The results can be produced by oral calculations.
According to this "addition", how much is it to add from 1 to 1000?
Output:
output an integer to indicate the answer

The meaning of the question: It is to find the digit sum of each number from 1 to 1000 and then add up, and then output the accumulated result.
Idea: Traverse it again and write a function to find the digit sum of each number.

The function code for finding the digital sum:

int f(int n)
{
    
    
    int n_sum=0;  //存放数位和结果
    while(n) //每位都加完后,n变为0了,循环就结束了
    {
    
    
        int temp=n%10; //求出每一位的数(最后面的那位数字)
        n_sum+=temp; // 每位数累加上去
        n/=10; //最后一位累加过后,将n除以10(让百位变十位,十位变个位,以此类推)
    }
    return n_sum; // 返回n这个数的数位和
}

Smart, you must understand [hee hee]
Insert picture description here
Then what we have to do is to traverse it again, and then call the function that calculates the digit sum, set a temporary variable, receive the digit sum of each number returned, and continue to accumulate Give sum, and then we can finally output sum, we can also comment out the code, and then just print the output result.

Complete code:

#include<iostream>
using namespace std;
typedef long long ll;

int f(int n)
{
    
    
    int n_sum=0;
    while(n)
    {
    
    
        int temp=n%10;
        n_sum+=temp;
        n/=10;
    }
    return n_sum;
}

int main()
{
    
    
    ll sum=0;
    for(int i=1;i<=1000;i++)
    {
    
    
        int x=f(i);
        sum+=x;
    }
    cout<<sum<<endl;
    return 0;
}

Don’t forget to like it after reading, thank you for your support!
If you are a computer terminal, you can also see the "one key triple connection" in the lower right corner, right click it [haha]

Insert picture description here
Come on!

Work together!

Keafmd

Guess you like

Origin blog.csdn.net/weixin_43883917/article/details/109255775
Recommended