【九度OJ】题目1124:Digital Roots 解题报告

时间:2023-03-08 17:02:27

【九度OJ】题目1124:Digital Roots 解题报告

标签(空格分隔): 九度OJ


原题地址:http://ac.jobdu.com/problem.php?pid=1124

题目描述:

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.

输入:

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.

输出:

For each integer in the input, output its digital root on a separate line of the output.

样例输入:

24
39
0

样例输出:

6
3

提示:

The integer may consist of a large number of digits.

Ways

这个题目的意思是,已知有个数字,把各位的数字加起来,如果和>=10,那么重复这个操作,直至为个位数。

另外特别提醒,有可能输入一个很大的数字,也就是没法直接使用int接受这个数字。

那么好,我用一个char接受这个数字,开了10000位的空间,应该够用。

第一遍循环,我求出了各位的和,现在一估算,这个数字不会大于100000,那么我之后就可以用int来操作了。23333

底下的步骤就是老一套,求余,把各位数字相加,然后循环。

前几次WA,原因是判断answer是不是个位数的时候,要注意answer>=10为条件,之前没写等号,故出错。

#include <stdio.h>
#include <string.h> int main() {
char str[10000];
while (scanf("%s", str) != EOF) {
int answer = 0;
if (strcmp(str, "0") == 0) {
break;
}
int len = strlen(str);
for (int i = 0; i < len; i++) {
answer += str[i] - '0';
}
while (answer >= 10) {//是大于等于,不是只有大于
int temp = answer;
answer = 0;//归零
while (temp > 0) {
answer += temp % 10;
temp /= 10;
}
}
printf("%d\n", answer);
} return 0;
}

另外根据上一篇文章的经验,可以使用sprintf函数。方法如下。

#include <stdio.h>
#include <string.h> int main() {
char str[10000];
while (scanf("%s", str) != EOF) {
if (strcmp(str, "0") == 0) {
break;
}
int answer = 10;//技巧
while (answer >= 10) {//是大于等于,不是只有大于
answer = 0;//每次循环归零
for (int i = 0; str[i] != 0; i++) {
answer += str[i] - '0';
}
sprintf(str, "%d", answer);//真的很方便啊!!!!
}
printf("%d\n", answer);
} return 0;
}

Date

2017 年 3 月 5 日