GDUFE ACM-1005

题目:http://acm.gdufe.edu.cn/Problem/read/id/1005

Digital Roots

Time Limit: 2000/1000ms (Java/Others)

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(the length of each integer will not exceed 1000), 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

思路:把各个位上的数字加起来,得出的和如果大于等于10,就继续循环,直到和小于10

难度:简单

代码:
 1 #include<stdio.h>
 2 #include<string.h>
 3 int main()
 4 {
 5     int i,b,sum;
 6     char ch[1000];
 7     while(scanf("%s",ch)!=EOF)
 8     {
 9         if(ch[0]=='0'&&strlen(ch)==1) break;
10         sum=0;
11         for(i=0;i<strlen(ch);i++)
12         {
13             sum=sum+ch[i]-48;
14         }
15         while(sum>=10)
16         {
17             b=sum;
18             sum=0;
19             while(b>=10)
20             {
21                 sum=sum+b%10;
22                 b=b/10;
23             }
24             sum=sum+b;
25         }
26         printf("%d
",sum);
27     }
28     return 0;
29 }
原文地址:https://www.cnblogs.com/ruo786828164/p/6005100.html