Digital Roots
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 50214 Accepted Submission(s): 15669
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.
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
水题题目大意就懒得说了,看题大家都懂了,数组记得开大点,第一次因为开了太小WA了一发,用了递归,开个字符数组和整形数组就搞定了,还有Linux下gcc好像gets竟然用不了,没办法只能用fgets(数组,size,stdin),遇到换行字符'\n'结束。下面贴下带代码:
#include<iostream>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxn = 100000;
char a[maxn];
int b[maxn];
void res(int len)
{
int sum = 0,cnt = 0,i;
for(i=0;i<len;i++)
{
sum += b[i];
}
memset(b,0,sizeof(b));
while(sum)
{
b[cnt++] = sum % 10;
sum = sum / 10;
}
if(cnt>1)//终止条件为cnt<=1
res(cnt);//递归求解
else
cout<<b[0]<<endl;//因为答案只有一位
}
int main()
{
int i;
while(fgets(a,maxn,stdin) && a[0] != '0')
{
int len = strlen(a);
for(i=0;i<len-1;i++)
{
b[i] = a[i] - '0';
//cout<<b[i]<<" ";
}
res(len);
}
}