(ACM)Digital Roots

来源:互联网 发布:apt-get insall yum 编辑:程序博客网 时间:2024/06/10 01:56

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

Source

Greater New York 2000

题意

题目的意思为将一个正整数的各位相加得到一个实数,若所得的实数的数字多余两个,则继续将该实数的各个数字相加直至所的的实数为一个数字。

自己编写的代码

#include <stdio.h>unsigned long B(unsigned long a);int main() {    unsigned long s,a,b,i,j=0,n[100000];    do{        i=j;        scanf("%d",&n[i]);        j++;    }while(n[i]!=0);    for(i=0;n[i]!='\0';i++)    {        if(n[i]>0)        {            a=n[i]/10;            b=n[i]%10;            while(a>=10)            {                a=B(a);            }            s=a+b;            if(s>=10)            {                a=s/10;                b=s%10;            }            s=a+b;            printf("%d\n",s);         }         else         {            return 0;         }    }    return 0;}unsigned long B(unsigned long a){    unsigned long m;    if(a>=10)    {        m=a/10+a%10;    }    return m;}

模仿他人的代码

#include <stdio.h>  #include <string.h>  int main()  {      int n,i;    char a[9999];    while(scanf("%s",a)!=EOF&&a[0]!= '0')    {          int s=0,n;          for(i=0;i<strlen(a);i++)        {            s+=a[i]-'0';        }          while(s>=10)          {              n=s;              s=0;              while(n)              {                  s+=n%10;                  n/=10;              }          }          printf("%d\n",s);      }      return 0;  } 

错误分析及心得

在自己编写代码时,多次因为整数所取的范围而不够导致代码审核不通过。然后通过百度学习其他人的代码发现:当所需的整数范围要求很大的时候,可以采用字符串数组,最后将字符的结束字符‘\0’减去,就可以得到所要的数字,从而避免整数越界。通过此题,可以加深自己对字符串数组的使用方法。