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
一、题意:
首先给出数字根的定义:数字根是将一 正整数的各个位数相加(即横向相加),若加完后的值大于10的话,则继续将各位数进行横向相加直到其值小于十为止,或是,将一数字重复做数字和,直到其值小于 十为止,则所得的值为该数的 数根。
本题的题目要求就是求出所给数字的数字根。
二、解法:
合九法:一个数的数字根等于这个数除以9的余数,也等于各位所有数之和除以9 的余数。
这里要注意的是,如果一个数各位所有数之和等于9,那就不用再除以9的余数了。所以,如果得到的答案是9,那么要强制赋值为9。
三、代码:
#include<iostream>
#include<string>
using namespace std;
int main()
{
string s;
int sum,ans;
while(cin>>s && s!="0")
{
sum = 0;
for(int i=0;i<s.length();i++)
sum+=s[i]-48;
ans = sum%9;
if(ans == 0)
ans = 9;
cout<<ans<<endl;
}
}