现在的位置: 首页 > 综合 > 正文

POJ 1519 Digital Roots — from lanshui_Yang

2019年01月08日 ⁄ 综合 ⁄ 共 1367字 ⁄ 字号 评论关闭

Description

The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is
repeated. This is continued as long as necessary to obtain a single digit. 

For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process
must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

Input

The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.

Output

For each integer in the input, output its digital root on a separate line of the output.

Sample Input

24
39
0

Sample Output

6
3

    题目大意很简单 ,就是输入一个数n,让你求n 的各位数字之和 m ,如果 m 大于10 ,则再求 m 的各位数字之和 m2,直到求出的和小于10为止。例如:n = 24 ,此时 n 的各位数字之和为6 (小于10),输出 6 ;又如 n = 39 ,此时 n 的各位数字之和为 12 (大于10),继续,12  的 各位数字之和为 3 (小于10),输出 3  ,结束~~
    Ps: 此题的难度在于 n 可能 很大很大 ,故 不能用int 来定义n,所以 要用到字符串~~
    具体解释请看程序:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cmath>
using namespace std;
int main()
{
    string t; // 用字符串定义 t (t 即为上述 n)
    while (1)
    {
        cin>>t;
        if(t=="0")
        break;
        int i;
        int sum = 0;
        int cur;
        for(i=0;i<t.length();i++) // 先计算 t 的各位数字之和
        {
            sum += (t[i]-'0');
        }
        while (sum >= 10)  // 以下为核心部分 ,好好理解 ~
        {
            cur = sum;
            sum = 0;
            while (cur)
            {
                sum += cur % 10;
                cur /= 10;
            }
        }
        printf("%d\n",sum);
    }
    return 0;
}

抱歉!评论已关闭.