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
//代码较弱,我的方法是不断的循环(目的是使各个位数之和加起来小于10)
#include<iostream>
#include<string.h>
#include<string>
using namespace std;
int main()
{
char a[10000];
int i,sum,t;
while(cin>>a)
{
sum=0;
t=0;
if(a[0]=='0')
break;
for(i=0;a[i];i++)
sum+=a[i]-'0';
if(sum<10)
cout<<sum<<endl;
while(sum>=10)
{
t+=sum%10;
sum=sum/10;//将各个位数加起来
if(sum<10)
{
t+=sum;
if(t>=10)//如果仍大于10的话,仍不断的循环直到各个位数和加起来小于10
{
sum=t;
t=0;
}
}
if(sum<10)//若小于10则输出
cout<<t<<endl;
}
}
return 0;
}//其实这道题是关于大数的,参看了别人的代码才知道可以用九余数定理,超级简单九余数定理:一个数对九取余后的结果称为九余数。一个数的各位数字之和相加后得到的<10的数字称为这个数的九余数(如果相加结果大于9,则继续各位相加)
#include<iostream>
#include<string.h>
#include<string>
using namespace std;
int main()
{
char a[10000];
int i,sum;
while(cin>>a)
{
sum=0;
if(a[0]=='0')
break;
for(i=0;a[i];i++)
sum+=a[i]-'0';
cout<<(sum-1)%9+1<<endl;
}
return 0;
}
362

被折叠的 条评论
为什么被折叠?



