HDU1013 Digital Roots

问题链接:HDU1013 Digital Roots。基础训练题,用C语言编写程序。

数根是指整数的各个位的数字之和。如果其和为1位数,则为结果;如果其和为多位整数,则再将各位数字相加,直到其和为1位数为止。

这个问题的大陷阱是,没有指出整数是多少位的。即使使用unsignde long long类型,也可能会溢出的。所以,需要先用字符串来处理。

其他的所有解释都在程序中了。

AC程序如下:

/* HDU1013 Digital Roots */

#include <stdio.h>

int main(void)
{
    char s[1024], *p;
    int digiroot;

    while(~scanf("%s",s)) {
        // 判断结束条件
        if(s[0] == '0')
            break;

        // 计算数根
        p = s;
        digiroot = 0;
        while(*p) {
            // step1 计算各位数字之和
            digiroot += *p++ - '0';

            // step2 每个10都变为1
            digiroot = digiroot / 10 + digiroot % 10;
        }

        // 输出结果
        printf("%d\n", digiroot);
    }

    return 0;
}


你可能感兴趣的:(digital,Roots,hdu1013,数根)