HDU1013 POJ1519 Digital Roots
该问题的最佳解法是利用数论的9余数定理来计算数根。一个数的数根等于该数的9的余数,若余数为0则结果为9。
问题链接:HDU1013 POJ1519 Digital Roots。基础训练题,用C语言编写程序。
问题简述:输入若干正整数,求其数根,直到输入为0为止。
问题分析:数根是指整数的各个位的数字之和。如果其和为1位整数,则为结果;如果其和为多位整数,则再将各位数字相加,直到其和为1位数为止。这个问题的大陷阱是,没有指出整数是多少位的。即使使用unsignde long long类型,也可能会溢出的。所以,需要按字符串来处理。
程序说明:(略)。
实际上可以一边读入数据一边处理,省去字符串数组,参见:HDU1013 POJ1519 Digital Roots(解法二)。
另外一个版本参见:HDU1013
POJ1519 Digital Roots(解法三)。
AC的C语言程序如下:
/* HDU1013 POJ1519 Digital Roots */ #include <stdio.h> int main(void) { char s[1024], *p; int digitroot; while(~scanf("%s",s)) { // 判断结束条件 if(s[0] == '0') break; // 计算数根 p = s; digitroot = 0; while(*p) { // step1 计算各位数字之和 digitroot += *p++ - '0'; // step2 每个10都变为1 digitroot = digitroot / 10 + digitroot % 10; } // 输出结果 printf("%d ", digitroot); } return 0; }