您的位置:首页 > 其它

HDOJ 1013 Digital Roots

2016-07-16 21:34 465 查看


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

题目大意:给出一个数,由它的各位数字相加得到一个新的数,重复此过程直到得到的数只有一位。刚开始不知道给出的数有几位,WA了N次,后来才知道要开数组存每一位。。。

解题思路:先把输入得到的字符数组转化为一个整数a,当a≥10的时候,调用solve函数求每一位的和直到a<10

代码如下:

#include <stdio.h>
const int maxn = 1005;
char s[maxn];

int solve(int a)
{
int b = 0;
while(a){
b += a % 10;
a /= 10;
}
return b;
}

int main()
{
int i;
int a,b;
while(scanf("%s",s) != EOF && s[0] != '0'){
a = 0;
for(i = 0;s[i] != '\0';i++)
a += s[i] - '0';

while(a >= 10)
a = solve(a);

printf("%d\n",a);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  HDOJ