ZeroJudge C813: Summing Digits

UVa 11332 – Summing Digits

For all positive integers N, we define a function f(N) as the sum of each decimal digit of N. If we repeatedly apply f(N) to itself, we obtain a function with many layers. Eventually, we reach a single-digit value, which we define as g(N).

When N = 1234567,

f(N) = 1 + 2 + 3 + 4 + 5 + 6 + 7 = 47

f(f(N) = 4 + 7 = 11

f(f(f(N))) = 1 + 1 = 2

So, g(1234567) is 2.

Sample Inputs/Outputs

Sample Input(s)Sample Output(s)
Each line of input contains a positive integer N, with values up to 2×10^9. You must output g(N). The input ends with a value of 0, which should not be output.As described in the input.
2
11
47
1234567892
0
2
2
2
2

Thought Process

Process each set of data using functions. When receiving data, use strings and determine their lengths. Convert the strings to integers for calculations.

Sample Code-ZeroJudge C813: Summing Digits

#include <iostream>
using namespace std;

int go (string str)
{
    if (str.length() == 1) return int(str[0] - '0');
    else
    {
        int sum = 0;
        for (int i = 0; i<str.length(); i++)
        {
            sum += int(str[i] - '0');
        }
        string tmp = to_string(sum);
        if (tmp.length() == 1) return int(tmp[0] - '0');
        else return go(tmp);
    }
}

int main() {
    string str;
    while (cin >> str)
    {
        if (str == "0") break;
        else
        {
            cout << go(str) << endl;
        }
    }
}

//ZeroJudge C813
//Dr. SeanXD

Comments