求数根

版权声明:本文为博主原创文章,转载请注明。 https://blog.csdn.net/qq_41181881/article/details/79368881

题目描述

给你一个数,对于一个数,把他所有位上的数字进行加和,得到新的数。
如果这个数字是个位数的话,那么他就满足条件,如果不满足条件 就继续让它重复以上操作。直到满足条件为止。

输入描述:

给一个整数数字n(1<=n<=1e9)。

输出描述:

输出由n经过操作满足条件的数
示例1

输入

12

输出

3

说明

12 -> 1 + 2 = 3

示例2

输入

38

输出

2

说明

38 -> 3 + 8 = 11 -> 1 + 1 = 2

代码讲解

#include <stdio.h>
int genshu(int a)//每一位相加的结果
{
    int t=0;
    while(a>0)
    {
        t=t+a%10;
        a=a/10;
    }
    return t;
}
int xunhuan(int a)//判断答案是否是个位数,是则返回,不是则循环
{
    int t;
    t=a;
    while(t>=10)//判断是否需要循环
    {
        t=genshu(t);
    }
    return t;
}
int main()//主函数
{
    int n;
    scanf("%d",&n);
    printf("%d",xunhuan(n));
}

猜你喜欢

转载自blog.csdn.net/qq_41181881/article/details/79368881