天天看點

HDU1013Digital Roots Digital Roots

Digital Roots

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 65378    Accepted Submission(s): 20386

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
        

  題目大意: 就是說超級數恩,什麼是超級數,就是一個正整數所有位置的數求和,得到的數,如果是個位數那麼這個 個位數就是超級數,如果不是個位數則需要将所得到的數的每個位置的數同上相加,直到得到的數字為個位數時,那麼這個數就是該數的超級數;

分析: 題目要求對每個輸入的正整數給出其超級數。剛開始的話我以為用 64位的整型就足夠了,結果WA了,那麼我就想到了,可以用字元串模拟改題,題目中給的資料将其每個位置的數加起來的值是會少于64位整型所能包括的數字,那麼題目就很簡單了,我隻要在原來WA的代碼的基礎上,将輸入的整型變成用字元串輸入,然後将其所有的字元轉換成整數并相加存到sum中,那麼接下來就是處理很簡單的整數的每個位置的相加就好了;

給出AC代碼:

#include<iostream>
#include<cstring>
using namespace std;
int main()
{
	char str[10000];
	while (cin >> str)
	{
		if (str[0] == '0')break;
		int len = strlen(str);
		long long sum = 0, n;
		for (int i = 0; i < len; i++)
			sum += (long long)(str[i] - '0');
		while (sum >= 10 || sum == 0)
		{
			if (sum >= 10)
			{
				n = sum;
				sum = 0;
			}
			int x;
			while (n)
			{
				x = n % 10;
				n = n / 10;
				sum += x;
			}
		}
		cout << sum << endl;
	}
	return 0;
}