杭电oj HDOJ 1013 Digital Roots
题目来源:http://acm.hdu.edu.cn/showproblem.php?pid=1013
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.
题目大意
“数字根”的计算方法是把一个数的每一位相加起来,如果得到的数只有一位,则得到的数就是原数的根,如果得到的数大于等于两位,再把这两位数加起来继续判断,直到得出一个一位数,它就是原数的根。现题目要求给出所有测试用例的“数字根”。
解题思路
这里解题思路就不再多提了,因为比较基础。我想提醒注意的是本题由于没有说明测试用例的范围,所以要使用“字符串型”来接收测试用例。
本人的C++解决方案
#include <iostream>
#include <stdio.h>
#include <string>
#include <sstream>
using namespace std;
int main()
{
string num;
int temp, len, i, root;
stringstream ss;
while (cin >> num) {
if (num == "0") {
break;
}
len = num.length();
// 如果该整数只有一位时,其根为本身
if (len == 1) {
ss << num;
ss >> root;
ss.clear();
}
while (len > 1) {
root = 0;
for (i = 0; i < len; i++) {
ss << num[i];
ss >> temp;
root += temp;
ss.clear();
}
ss << root;
ss >> num;
ss.clear();
len = num.length();
}
printf("%d\n", root);
}
return 0;
}
代码通过HDOJ平台运行检查,如发现错误,欢迎指出和纠正,谢谢!