Digital Roots
24 39 0
6 3
#include<cstdio>
#include<cstring>
void zuo(int x){
int sum=0;
while(x){
sum+=(x%10);
x/=10;
}
if(sum<10) printf("%d\n",sum);
else zuo(sum);
}
int main(){
char s[1010];
while(scanf("%s",s)&&s[0]!='0'){
int x=0;
for(int i=0;i<strlen(s);i++)
x+=(s[i]-'0');
zuo(x);
}
return 0;
}
还有一种解法,数论的知识。
数字本身: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 12 22 23 24 25 26 27 28 29 30············
各个位数和: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 3·············
你会发现,每9个是一个循环,所以只要对9取余就ok了。代码如下:
#include<cstdio>
#include<cstring>
int main(){
char s[1010];
while(scanf("%s",s)&&s[0]!='0'){
int x=0;
for(int i=0;i<strlen(s);i++)
x+=(s[i]-'0');
x=x%9;
if(x==0) printf("9\n");
else printf("%d\n",x);
}
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
HDU 1013.Digital Roots【模拟或数论】【8月16】
原文地址:http://blog.csdn.net/a995549572/article/details/47703513