Digital Roots
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 65378 Accepted Submission(s): 20386
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
题目大意: 就是说超级数恩,什么是超级数,就是一个正整数所有位置的数求和,得到的数,如果是个位数那么这个 个位数就是超级数,如果不是个位数则需要将所得到的数的每个位置的数同上相加,直到得到的数字为个位数时,那么这个数就是该数的超级数;
分析: 题目要求对每个输入的正整数给出其超级数。刚开始的话我以为用 64位的整型就足够了,结果WA了,那么我就想到了,可以用字符串模拟改题,题目中给的数据将其每个位置的数加起来的值是会少于64位整型所能包括的数字,那么题目就很简单了,我只要在原来WA的代码的基础上,将输入的整型变成用字符串输入,然后将其所有的字符转换成整数并相加存到sum中,那么接下来就是处理很简单的整数的每个位置的相加就好了;
给出AC代码:
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char str[10000];
while (cin >> str)
{
if (str[0] == '0')break;
int len = strlen(str);
long long sum = 0, n;
for (int i = 0; i < len; i++)
sum += (long long)(str[i] - '0');
while (sum >= 10 || sum == 0)
{
if (sum >= 10)
{
n = sum;
sum = 0;
}
int x;
while (n)
{
x = n % 10;
n = n / 10;
sum += x;
}
}
cout << sum << endl;
}
return 0;
}