題意:整數的樹根,即當整數不為單獨的數字時将各個位上的數字相加,直到為單個數字時輸出此時的數字。
解題思路:利用字元串進行處理,詳見代碼:
Code:
#include <iostream>
#include <string>
using namespace std;
string add(string &a)
{
string result;
int c=0,i,carry=0,len=a.size();
c=(a[len-1]-'0');
for(i=len-2;i>=0;--i)
{
c+=(a[i]-'0');
if(c>10)
{
carry=c/10;
c%=10;
result.push_back(carry+'0');
}
}
result.push_back(c+'0');
return result;
}
int main()
{
string result;
while(cin>>result)
{
if(result=="0") break;
else
{
while(result.size()>1)
result=add(result);
cout<<result<<endl;
}
}
return 0;
}
再來個經典的代碼:
#include<stdio.h>
int main()
{
int i,m;
char s[1000];
while(scanf("%s",s)==1&&s[0]!='0'){
for(m=i=0;s[i];i++)
m+=s[i]-'0';
printf("%d\n",m%9==0?9:m%9);
}
return 0;
}