Digital Roots
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 19968 | Accepted: 6563 |
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
63
Source
此题题意不难理解;题目所要处理的问题主要使用int型(一个数字占两个字节内存)(即使是long long int型)无法对庞大的数值进行存储(即使是long long int型)。所以使用char 型进行存储(一个字符占一个字节内存),问题关键就在如何将用char类型存储的数字转换成整型。
解决方法:字符-‘0’ ;如字符 ‘5’ - ‘0’ =整型0,则字符串“12345”由循环语句- ‘0’ 就可以依次得到整型1 2 3 4 5 。
源代码:
#include<iostream>
using namespace std;
int main()
{
char no[1001];
int i,temp=0,sum=0;
while(cin>>no&&no[0]!='0')
{
for(i=0;no[i]!='\0';i++)
temp+=no[i]-'0';
while(true)
{
sum+=temp%10;
temp/=10;
if(sum>9&&temp==0)
{
temp=sum;
sum=0;
}
if(sum<10&&temp==0)
{
cout<<sum<<endl;
sum=temp=0;
break;
}
}
}
return 0;
}