原题:http://acm.hdu.edu.cn/showproblem.php?pid=1013
思路:
题干的意思很简单,即把每一位数加起来,until<10。读入的数据可能会很大,这里使用字符串进行操作。
源代码:
#include <cstdio> #include <string> #include <cstring> int main() { char str[10000]; while (scanf("%s", str) != EOF) { if (strcmp(str, "0") == 0) //判断退出条件 { break; } int answer = 10; //Key,进入循环 while (answer >= 10) { answer = 0; for (int i = 0; str[i] != 0; i++) { answer += str[i] - '0'; //直接相减再强制转换就是对应的数字 } sprintf(str, "%d", answer); //这个库函数非常好用,int to string } printf("%d\n", answer); } return 0; }