题目(http://acm.hdu.edu.cn/showproblem.php?pid=1013)
一开始不知道计算数根的公式,直接做也能过,数据很大要用字符串
#include <iostream>
#include <string.h>
using namespace std;
char n[1000000];
int main()
{while(cin>>n)
{
if(n[0]=='0')
break;
int sum=0;
for(int i=0;n[i]!='\0';i++)
{
sum+=n[i]-'0';
if(sum>9)
sum=sum%10+sum/10;//及时处理
}
cout<<sum<<endl;
}
return 0;
}
后来看别人的代码,知道数论这回事;
n=0 1 2 3 4 5 6 7 8 9 10 11 12 13 ……… 100 101 102 103 ….
roots=0 1 2 3 4 5 6 7 8 9 1 2 3 4 …….1 2 3 4….
原来是以1…..9为循环节的,每次增加1,那么层层迭代下来,最终当ans<10的时候也是每次增加了1。如此,可以归纳出
roots=(n-1)%9+1.不能直接模9,单位数9就输出9,直接模就是0了;
#include <iostream>
#include <string.h>
using namespace std;
char n[1000000];
int main()
{while(cin>>n)
{
if(n[0]=='0')
break;
int sum=0;
for(int i=0;n[i]!='\0';i++)
sum+=n[i]-'0';
cout<<(sum-1)%9+1<<endl;
}
return 0;
}