HDU 1013 Digital Roots(九余数定理 + 暴力解法)

  • Digital Roots

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

题意:给一个整数,如果它是个位数那么这个数的根就是它本身,否则等于它各个位上数字的和,如果和也不为个位数,则依此递推,例如12的根为3,39的根为3。当输入为0时结束。
这个题目乍一看好像挺简单,但还是有点坑,就是它的数据范围没有给出来,用int 和 long long 都不行,只能用字符串去存储。
方法一:暴力解先用字符串存储整数,然后将各位数字相加存到整数中去,后面操作就很简单了
下面是AC代码

#include 
#include 
#include 
using namespace std;

int main()
{
	string str;
	while(cin>>str && str != "0"){
		int sum = 0;
		int len = str.length();
		for(int i = 0; i < len; i++)
		{
			sum += str[i] - '0';
		}
		while(sum >= 10)   //当sum为个位数时退出循环
		{
			int d = 0;
			while(sum){   //将sum中的各位数字累加至d中
				d += sum % 10;
				sum /= 10;
			}
			sum = d;
		}
		printf("%d\n", sum);
	}
	return 0;
}

方法二:这种方法十分简单,只需要用九余数定理就可以轻松解决,九余数定理就是一个数的根等于它各位上的数字累加和对9取模,推导如下:

图片
图片
10^i-1对9取模为0,所以n对9取模等于各位上的数字的累加和。
后面就很简单了,直接给出代码:

#include 
#include 
#include 
using namespace std;

int main()
{
	string str;
	while(cin>>str && str != "0"){
		int sum = 0;
		int len = str.length();
		for(int i = 0; i < len; i++)
		{
			sum += str[i] - '0';
		}
		sum %= 9;
		if(sum == 0) printf("9\n");
		else
			printf("%d\n", sum);
	}
	return 0;
} 

End

你可能感兴趣的:(题解,字符串,算法,c++)