题目:http://acm.hdu.edu.cn/showproblem.php?pid=1013
输入一串数字,把各个位上的数字相加,直到剩一位数。求那一位数。
例如39,3+9=12,1+2=3,结果为3.
思路:简单的字符串处理。可以用九余数定理。
九余数定理就是一个数对九取余,得到的数称之为九余数;一个数的九余数等于它的各个数位上的数之和的九余数!
39对9取余,为3.,过程中12对9取余还是3. 例如77,对9取余5,7+7=14,1+4=5.本质上就是9余数(因为取个位数。)
方法一:模拟
#include<iostream>
using namespace std;
int func(int n)
{
int digit = 1; int ans=0;
while (n / 10 != 0)
{
ans += n % 10;
n = n / 10;
digit++;
}
ans += n % 10;
if (ans < 10)
return ans;
else return func(ans);
}
int main()
{
int n=0; char a[1000];
while (cin >> a)
{
n = 0;
if (a[0]=='0')
break;
for (int i = 0; a[i] != '\0'; i++)
n += a[i] - '0';
cout << func(n) << endl;
}
return 0;
}
方法二:九余数
#include<stdio.h>
int main()
{
int s;
char c;
while(1)
{
s=0;
while(scanf("%c",&c)&&c!='\n')
s+=c-'0';
if(!s)return 0;
else if(s%9==0)puts("9");
else printf("%d\n",s%9);
}
return 0;
}