hdu1013:Digital Roots



Digital Roots

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 49017    Accepted Submission(s): 15249


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
 

Recommend
We have carefully selected several similar problems for you:  1008 1017 1012 1002 1005 
 以後要注意:若該數很大,int類型可能放不了,這時要考慮用getchar()來處理,用數組來存儲。
但該題不需用數組存儲大數,只需求出該大數位上和再進行若干操作即可。
注意到:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
                               1  2  3   4     5    6   7  8  9 
                                                                          19 20 21 22 23 24 25 26 27......................................................
                                                                              1 2  3  4   5   6   7   8   9
從上面看出是一1到9爲一個週期,便得下面代碼。
#include<iostream>
#include<cstdio>
#include<string>
#include<stack>
#include<queue>
#include<algorithm>

using namespace std;

int main()
{
	int sum=0;
	char c;
    //freopen("in.txt", "r", stdin);
    while (true){
		sum=0;
		while((c=getchar())!='\n'){
			sum+=c-'0';
		}
		if(sum==0)
			break;
		int m=sum%9;
		if(m==0){
			printf("9\n");
		}
		else
			printf("%d\n",m);
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章