首页 > ACM题库 > HDU-杭电 > HDU 1013 Digital Roots-模拟-[解题报告] C++
2013
11-26

HDU 1013 Digital Roots-模拟-[解题报告] C++

Digital Roots

问题描述 :

The digital root of a positive integer is found by summing the digits of the integer. If the resulting value is a single digit then that digit is the digital root. If the resulting value contains two or more digits, those digits are summed and the process is repeated. This is continued as long as necessary to obtain a single digit.

For example, consider the positive integer 24. Adding the 2 and the 4 yields a value of 6. Since 6 is a single digit, 6 is the digital root of 24. Now consider the positive integer 39. Adding the 3 and the 9 yields 12. Since 12 is not a single digit, the process must be repeated. Adding the 1 and the 2 yeilds 3, a single digit and also the digital root of 39.

输入:

The input file will contain a list of positive integers, one per line. The end of the input will be indicated by an integer value of zero.

输出:

For each integer in the input, output its digital root on a separate line of the output.

样例输入:

24
39
0

样例输出:

6
3

解题报告:

题目大意:给定一个正整数N,求这个数的“根”,这里的根指的是:若N是个位数,则它的根就是N,若N是两位或两位以上的数,则的它的根就等于N的各位的和,若它的各位的和任然是两位或两位以上,则再求这个和的各位的和,直到这个各位的和是一个个位数。就是N的根。

模拟题,但要注意的是这个N的范围很大,要用数组模拟。

1 #include<cstdio>
 2 #include<cstring>
 3 int main() {
 4     int N,ans=0;
 5     char str[1000];
 6     while(scanf("%s",str)) {
 7         if(strlen(str)==1&&str[0]=='0')
 8         break;
 9         while(1) {
10             int len=strlen(str);
11             if(len==1) {
12                 printf("%s\n",str);
13                 break;
14             }
15             ans=0;
16             for(int i=0;i<len;++i)
17             ans+=str[i]-'0';
18             int z=0;
19             while(ans!=0) {
20                 str[z++]=(ans%10)+'0';
21                 ans/=10;
22             }
23             str[z]=NULL;
24         }
25     }
26     return 0;
27 }
28

 


  1. #include <stdio.h>
    int main()
    {
    int n,p,t[100]={1};
    for(int i=1;i<100;i++)
    t =i;
    while(scanf("%d",&n)&&n!=0){
    if(n==1)
    printf("Printing order for 1 pages:nSheet 1, front: Blank, 1n");
    else {
    if(n%4) p=n/4+1;
    else p=n/4;
    int q=4*p;
    printf("Printing order for %d pages:n",n);
    for(int i=0;i<p;i++){
    printf("Sheet %d, front: ",i+1);
    if(q>n) {printf("Blank, %dn",t[2*i+1]);}
    else {printf("%d, %dn",q,t[2*i+1]);}
    q–;//打印表前
    printf("Sheet %d, back : ",i+1);
    if(q>n) {printf("%d, Blankn",t[2*i+2]);}
    else {printf("%d, %dn",t[2*i+2],q);}
    q–;//打印表后
    }
    }
    }
    return 0;
    }