HDOJ-1013

Digital Roots

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 67912    Accepted Submission(s): 21226


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

本题题意很简单,给你一个非负整数,要求整数的每一位相加的和为一位整数,如果不是,则对得到的和继续每一位相加操作,直至其和为一位整数。

题目中举出了两个例子,当非负整数位24时,第一次处理相加和为6,是一位整数,所以输出6;当非负整数为39时,第一次处理和为12,故再处理一次,各位相加和为3,符合输出。

我的方法是写一个函数Do()来实现每一次处理直至最后的和为一位数。

附AC代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 
 7 char a[1010];
 8 
 9 int Do(int sum){//每位相加返回和 
10     int ans=0;
11     while(sum>=10){
12         ans+=sum%10;
13         sum/=10;
14     }
15     ans+=sum;
16     return ans;
17 }
18 
19 int main(){
20     while(gets(a)&&a[0]!='0'){//输入待处理数据 
21         int sum=0;
22         for(int i=0;i<strlen(a);i++){//求第一次和 
23             sum+=a[i]-'0';
24         }
25         while(sum>=10){//当最后的值大于两位,再处理 
26             sum=Do(sum);
27         }
28         printf("%d
",sum);
29     }
30     return 0;
31 } 
原文地址:https://www.cnblogs.com/Kiven5197/p/5487304.html