树根
Appoint description:
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.
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
是位数上的和相加,一直到和为一位数:
你可以这么写:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <stack>
#include <cstring>
using namespace std;
#define INF 0xfffffff
#define maxn 1200
#define min(a,b) (a<b?a:b)
#define max(a,b) (a>b?a:b)
int Root(int n)
{
if(n < 10)
{
return n;
}
int a = 0;
while(n)
{
a += n%10;
n /= 10;
}
Root(a); //递归,因为要做的步骤一样
}
int main()
{
char str[maxn];
int n;
while(cin >>str, strcmp(str, "0"))
{
n = 0;
for(int i=0; str[i]; i++)
n += str[i] - '0';
n = Root(n); // 就是正常思维一步步求树根
cout << n << endl;
}
return 0;
}
你也可以这么写:
#include<stdio.h>
#include<string.h>
char s[1010];
int main()
{
int sum,i,len,x;
while(gets(s)&&s[0]!='0')
{
sum=0;
len=strlen(s);
for(i=0;i<len;i++)
sum+=s[i]-'0';
x=sum%9; // 求余9是因为十进制满10进1,38%9 = 2;38的树根是,3 + 8 = 11, 1 + 1 = 2,是2;自己悟=。=||
if(x==0) x+=9;
printf("%d
",x);
}
return 0;
}