思路
求解数字根,要注意的是数据是大数,需要处理。或者根据定理来进行求解。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
int num, ans;
char str[1000];
while(scanf("%s", str) && str[0]!='0')
{
num = 0;
// 处理过一次后的数据便可以用 int 存下来
for(int i=0; str[i]!='\0'; i++) num += (str[i] - '0');
while(num>9)
{
ans = 0;
while(num)
{
ans += num%10;
num /= 10;
}
num = ans;
}
printf("%d\n", num);
}
return 0;
}
利用定理
另一种解法,wiki上的解释。
⎧⎩⎨0 if n=0,9 if n≠0, n≡0(mod 9),n mod 9 if n≢0 (mod 9)
整理就是 d(n)=1+(n−1) mod 9
代码
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
int num;
char str[1000];
while(scanf("%s", str) && str[0]!='0')
{
num = 0;
for(int i=0; str[i]!='\0'; i++) num += (str[i] - '0');
printf("%d\n", 1+(num-1)%9);
}
return 0;
}