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

HINT

 

http://acm.hdu.edu.cn/showproblem.php?pid=1013

/*
由于不知道所求的数有多少位数,因此使用字符数组,以便存下上千位的整数,
在反复的求各位数的和时,纯粹的使用字符做比较麻烦,因此使用整数逐位求和。
*/

#include<stdio.h>
int loop(int sum1){                  //调用函数进行反复求和
 int i,sum2=0;
 for(i=0;i<5;i++){                  //即使输入的位数有1000位,在第一次求和之后将不超过五位
  sum2+=sum1%10;              //每次提取一个数位求和
  sum1/=10;                           //提取完后准备下一位
 }
 return sum2;
}
int main(){
 char a[1001];   
 int i,sum=0,sum1=0;
 gets(a);
 while(a[0]!='0'){
 for(i=0;a[i]!='\0';i++)
  sum+=(int)(a[i]-48);             //将字符转化为整数,并求和
 for(i=0;i<5;i++){
  sum1+=sum%10;
  sum/=10;
 }
 while(sum1>=10)
  sum1=loop(sum1);                 //判断sum1的位数
 printf("%d\n",sum1);
 sum=sum1=0;                          //结束处理后要将求和时所用的数据清零
 gets(a);
 }
 return 0;
}

 

发表评论

电子邮件地址不会被公开。

Post Navigation