通过这个题应该知道,当题目中没有给出明确限制时,也要考虑到最坏的情况,此题并没有说数字会有多长,如果直接用int、long、usigned的类型去做,就会产生错误,明智之举是用string,它不用考虑分配多少内存。
#include <iostream>
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
freopen("in.txt","r",stdin);
string str;
int i,len,num,res;
while(cin >> str && str != "0")
{
len = str.size();
num = 0;
for(i = 0;i < len;++i)
num += str[i] - '0';
while(true)
{
res = 0;
while(num > 0)
{
res += num % 10;
num /= 10;
}
if(res < 10)
{
cout << res << '/n';
break;
}
else
num = res;
}
}
return 0;
}