Digital Roots

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 19   Accepted Submission(s) : 7
Font: Times New Roman | Verdana | Georgia
Font Size: ← →

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
//递归写法
#include<cstdio>
#include<cstring>
__int64 fun(__int64 n){
    __int64 s=0;
    while(n>0){
        s+=n%10;
        n/=10;
    }
    if(s>9)return fun(s);
    return s;
} 
int main(){
    char str[10010];
    int i,j,n;
    while(scanf("%s",str)&&strcmp(str,"0")){
        int len=strlen(str);
        for(i=0,n=0; i<len; i++){
            n+=str[i]-'0';
        }
     //   printf("***%d\n",n);
        printf("%d\n",fun(n));
    }
    return 0;
}


Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐