【杭电】1013【 Digital Roots】 犯下的错误

来源:互联网 发布:北大医学部知乎 编辑:程序博客网 时间:2024/06/05 14:32

                                 Digital Roots
              Time Limit: 2000/1000 MS (Java/Others)    

                 Memory Limit: 65536/32768 K (Java/Others)
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

用字符串来保存数字可以做到每个数字独立,且每个数字范围为0~9,而我一开始的想法就是输入一个数字的字符串数组,我计算所有数字的总和,然后再把这个和sum的每个数字再存入数字的字符串数组,后面的做法就跟前面一样了,而循环的终止条件就是总和sum<10.




首先,这看之下,这题目,太简单了,加法循环跳出就OK了啊


#include<stdio.h>#include<math.h>int main(){    int a,b;    while (scanf("%d", &a) ==1 && a)    {      b=0;      while(a)      {          if(a<10)            {              b+=a;a=0;          }          else {b+=a/10;a=a%10;}          if(!a && b>9){a=b;b=0;}        }       printf("%d\n",b);       }    return 0;}



咔咔咔咔 得 就写完了, 完事还挺高兴的(毕竟初学者嘛)  结果一直报Wrong Answer ,想了半天,才发现  数字会溢出



所以有了下面这个简洁的代码



#include<stdio.h>int main(){ int i,m; char s[1000]; while(scanf("%s",s)==1&&s[0]!='0') {     for(m=i=0;s[i];i++)               m+=s[i]-'0';     printf("%d\n",m%9==0?9:m%9);  } return 0;}

哈哈哈,真是机智!!!!

0 0
原创粉丝点击