(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’减去,就可以得到所要的数字,从而避免整数越界。通过此题,可以加深自己对字符串数组的使用方法。
- (ACM)Digital Roots
- ACM Digital Roots
- 北大ACM poj1519 Digital Roots
- [ACM - 数论]Eddy's digital Roots(九余数定理)
- hdu1013(Digital Roots)
- 杭电ACM 1013 Digital Roots
- 杭电acm 1013 Digital Roots
- 杭电ACM-1013-Digital Roots
- 杭电ACM 1013 Digital Roots
- HDU's ACM 1013 Digital Roots
- 杭电 acm 1013 Digital Roots
- ACM 数论 hdu 1013 Digital Roots
- 杭电acm—1013 Digital Roots
- HDU1013 - Digital Roots (模拟)
- Digital Roots
- Digital Roots
- Digital Roots
- Digital Roots
- 【C++】判断是不是2、3、4的幂数
- 转载自博客园不思蜀的转载文章:最大子序列和算法分析
- 171120-函数程序练习【连续第二十八天】
- mybatis入门之简单操作
- 通俗易懂的依赖注入
- (ACM)Digital Roots
- 实验6 图的遍历
- (四) java并发编程--线程安全和资源共享
- 欢迎使用CSDN-markdown编辑器
- OpenStack虚拟机创建流程
- springMVC解决跨域jsonp乱码问题的三种方法
- jvm内存模型
- caffe python接口 测试分类:
- 用一个例子看const与指针、引用、多级指针结合的区别