HDOJ 1013 Digital Roots
2016-07-16 21:34
465 查看
Digital Roots
Problem DescriptionThe 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
题目大意:给出一个数,由它的各位数字相加得到一个新的数,重复此过程直到得到的数只有一位。刚开始不知道给出的数有几位,WA了N次,后来才知道要开数组存每一位。。。
解题思路:先把输入得到的字符数组转化为一个整数a,当a≥10的时候,调用solve函数求每一位的和直到a<10
代码如下:
#include <stdio.h> const int maxn = 1005; char s[maxn]; int solve(int a) { int b = 0; while(a){ b += a % 10; a /= 10; } return b; } int main() { int i; int a,b; while(scanf("%s",s) != EOF && s[0] != '0'){ a = 0; for(i = 0;s[i] != '\0';i++) a += s[i] - '0'; while(a >= 10) a = solve(a); printf("%d\n",a); } return 0; }
相关文章推荐
- 2015 Multi-University Training Contest 6 Solutions
- HDOJ 1002 A + B Problem II (Big Numbers Addition)
- Sum Problem
- HDOJ 1009
- HDOJ 1001 递归方法
- HDOJ 1002 C语言版
- HDOJ 1003题解
- Big Number
- hdoj 2036 改革春风吹满地
- hdu 3076 ssworld VS DDD 概率dp
- hdu5007 ACM-ICPC 西安赛区网赛A题 水题
- hdu5011 西安邀请赛E题 Game 博弈论
- hdu5012 ACM-ICPC 西安赛区E题 Dice
- hdoj2029 Palindromes _easy version
- hdoj 2031 进制转换
- hdoj 2033 人见人爱
- hdoj 1874 畅通工程 vector邻接表测试
- 最小生成树——HDOJ 1233 还是畅通工程 解题报告
- 并查集——HDOJ 1213How Many Tables解题报告
- 最小生成树——HDOJ 2988 Dark roads解题报告