#**

5月20日本该告白的日子,我却在这里码代码,程序员的日子可能就是这样吧,悲催催,不说了,上干货

**
相信你们都查过翻译了,那我就不翻译了~~(主要因为太懒)~~
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
如果你和我一样直接用int,哈哈,恭喜你,他一定提示你wd,
即使用long long int 也一样会提示为WD

#include<iostream>
using namespace std;
void digdtalNum(long long int N)
{
 int sum = N % 10;
 if ( N < 10)
 {
  cout << N << endl;
 }
 else
 {
  while (N >= 10)
  {
   N /= 10;
   sum += N % 10;
  }
  if (sum >= 10)
  {
   digdtalNum(sum);
  }
  else
   cout << sum << endl;
 }
}
long long int N;
int main()
{
 
 while (cin >> N && N != 0&&N>0)
 {
  digdtalNum(N);
 }
 return 0;
}

最后换成了字符串才解决

#include<iostream>
using namespace std;
#include<string.h>
int main()
{
	char N[9999];
	while (cin>>N && N[0] != '0')
	{
		int l = strlen(N);
		int num=0;
		for (int i = 0; i < l; i++)
		{
			num += N[i]-'0';
			if (num >= 10)
				num = num / 10 + num % 10;
		}
		cout << num << endl;
	}
	return 0;
}

其实这道题主要运用了同余定理及其相关应用,若想看可以参考我以前的这篇文章点击同余定理查看。

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐