题目

{% raw %}

点击显/隐题目
{% endraw %} 计算该整数的各位数字之和,如果结果值是单个数字的数,那么这个数就是所求数根;如果结果值是由两位数或两位以上的数字组成的数,则继续计算各位数 字的和,直到结果值只有一位数字为止。 24, 2+4=6, 则根是6 39, 3+9=12,1+2=3,根是3

{% raw %}



{% endraw %}

输入包括多组数据,每组测试数据包括一个正整数,并且占一行,输入数据为0时,表示输入结束。

{% raw %}



{% endraw %}

对于每组测试数据,给出对应输出,并且每组输出占一行

{% raw %}





{% endraw %}

24
39
0

{% raw %}



{% endraw %}

6
3

{% raw %}




{% endraw %}

题解

模拟就行,把每一位都取出来然后加起来,如果不是一位的数就继续循环
注意貌似 cin cout 会出错,换用 scanf 和 printf 吧

代码

点击显/隐代码
```cpp 数根 https://github.com/OhYee/sourcecode/tree/master/ACM 代码备份 /*/ #define debug #include //*/ #include #include #include using namespace std;

int main(){
#ifdef debug
freopen("in.txt", "r", stdin);
int START = clock();
#endif
cin.tie(0);
cin.sync_with_stdio(false);

int n;
while(scanf("%d",&n)!=EOF){
    if(n==0) 
        break;

    while(n>=10){
        int t = 0;
        while(n){
            t += n%10;
            n /= 10;
        }
        n = t;
    }
    printf("%d\n",n);
}

#ifdef debug
printf("Time:%.3fs.\n", double(clock() - START) / CLOCKS_PER_SEC);
#endif
return 0;

}

</div>