Digital Roots

Problem 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

Source
Greater New York 2000
题目网址:(http://acm.hdu.edu.cn/showproblem.php?pid=1013)

翻译:

问题描述
通过对整数的数字求和来找到正整数的数字根。如果结果值是单个数字,则该数字是数字根。如果结果值包含两个或更多个数字,则对这些数字求和并重复该过程。只要需要获得一位数,这就会继续。

例如,考虑正整数24.加上2和4得到值6.由于6是单个数字,6是24的数字根。现在考虑正整数39.3加上9 的和是12.由于12不是一个数字,因此必须重复该过程。1加上2的和是3,是单个数字,是39的数字根。

输入
输入文件将包含一个正整数列表,每行一个。输入的结尾将由整数值零表示。

输出
对于输入中的每个整数,在输出的单独行上输出其数字根。

样例输入

24
39
0

样例输出

6
3

题意:

整数的数字求和来找到正整数的数字根。如果结果值是单个数字,则该数字是数字根。

分析:

  1. 如果输入的数字,其各位上的数字加在一起是一位数,该和就是所求,如果不是,就进行循环(各位数字加和,然后判断是否是一位数)直到和是个一位数。
  2. 输入以 0 为结束标志,
  3. 题中没说输入 该数的范围,且数字应该是正整数,故 联系第二点 输入的数 是一个大于等于零的整数

代码:

#include <iostream>
include <stdio.h>using namespace std;
int main()
{
    string s;
    while(cin>>s&&s!="0")//以字符串输入一个数
    {
        long long d=0,x;
        for(int i=0;i<s.size();i++)//求该数的各位数字之和
           d+=(s[i]-'0');
           /*
           如果该和不是一位数(该数可能是一个很大的数字,
           使得第二次.第三次..该和不是一位数)
           如果该和是一位数,则输出
           */
           while(d>9) //如果该和不是一位数(该数可能是一个二位数,三位数..)           {
            {
                x=d;    //用 x 来进行循环,判断该数是不是一位数
               d=0;    //接受各位数字的的和
               while(x)
               {
                   d+=x%10;//求得个位数字的和
                   x/=10;  //换下一位
               }
            }
               printf("%lld\n",d);
           }
    return 0;
}

运行结果:

总结:数字的和比不一定是二位数,所以记得要多次对所得数字求和

猜你喜欢

转载自blog.csdn.net/shuisebeihuan/article/details/81156751