天天看點

杭電ACM 1013 Digital Roots問題分析與算法設計測試結果截圖

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
  
  
   

          

問題分析與算法設計

題目要求求出一個整數的根,并且整數可能無限大,是以考慮用字元串來儲存數字,這樣可以使各位數字相對獨立,且每個數字範圍為0~9,首先将字元串數組每一項轉換成數字形式,這裡用到了sum+=str[i]-‘0’,然後求出第一次各位數字相加的和。用sum模除10讀出個位數位,然後用整除10得到sum減去個位的值,再将兩者作和,如此循環,終止條件是sum模除10讀出個位數位等于自身,這就表明此時sum的值即為該整數的根。

源碼如下:

#include <iostream>
#include <string>
using namespace std;

int main()
{
	string str;
	while(cin>>str&&str!="0") 
	{
		int sum=0;
		for(int i=0;i<str.length();i++)
			sum+=str[i]-'0';
			while(sum%10!=sum)
			{
				int a=sum%10;
				int b=sum/10;
				sum=a+b;
			}
			cout<<sum<<endl;
	}
	return 0;
}
           

測試結果截圖

杭電ACM 1013 Digital Roots問題分析與算法設計測試結果截圖
杭電ACM 1013 Digital Roots問題分析與算法設計測試結果截圖

繼續閱讀