PAT 2-06 数列求和(C语言实现)

来源:互联网 发布:mac迅雷 浏览器打开 编辑:程序博客网 时间:2024/05/01 18:26

题目描述:

给定某数字A(1<=A<=9)以及非负整数N(0<=N<=100000),求数列之和S = A + AA + AAA + … + AA…A(N个A)。例如A=1, N=3时,S = 1 + 11 + 111 = 123。

输入格式说明:

输入数字A与非负整数N。

输出格式说明:

输出其N项数列之和S的值。

样例输入与输出:

序号输入输出1
1 3
123
2
6 100
7407407407407407407407407407407407407407407407407407407407407407407407407407407407407407407407407340
3
1 0
0

解答说明:
由于和S特别大,所以不可能直接求和计算,否则肯定会运行超时或者内存超限。
可以把求和写成算式的形式
如A+AA+AAA写成
    AAA
      AA
        A
这样和的个位肯定是A*3%10,十位肯定是(A*2+A*3/10)%10,以此类推。
可以用堆栈保存每一位的结果,最后再输出即可。

源码:
#include<stdio.h>#include<stdlib.h>typedef struct Node *ptrNode;typedef ptrNode stack;typedef int ElementType;struct Node{     ElementType Element;     ptrNode next;};/*检验是否空栈*/int IsEmpty(stack S){    return S->next == NULL;}/*销毁一个站,置空*/void MakeEmpty(stack S){    if(S == NULL){        printf("stack is already empty");        exit(0);    }    else        while(!IsEmpty(S))            popAndReturnTop(S);}stack Createstack(void){    stack S;    if((S = malloc(sizeof(struct Node))) == NULL){//不要少了括号!!!        printf("Unable to allocate memory");        exit(0);    }    S->next = NULL;    MakeEmpty(S);    return S;}void push(ElementType x, stack S){    ptrNode TmpCell;    TmpCell = malloc(sizeof(struct Node));    TmpCell->Element = x;    TmpCell->next = S->next;    S->next = TmpCell;}ElementType popAndReturnTop(stack S){    ptrNode TmpCell;    ElementType TopElement;    if(S == NULL){        printf("Empty stack");        exit(0);    }    else{        TmpCell = S->next;        S->next = S->next->next;        TopElement = TmpCell->Element;        free(TmpCell);    }    return TopElement;}int main(void){    int A, N;    int i,m,n,carry,temp;    stack s;    s = Createstack();    scanf("%d%d",&A,&N);if(N == 0)printf("0");    carry = 0;    for(i = N; i>0;i--){        n = i * A + carry;        m = n % 10;        carry = n / 10;        if(i != 1)            push(m,s);        else            push(n,s);    }    while(!IsEmpty(s)){        temp = popAndReturnTop(s);        printf("%d",temp);    }    return 0;}

0 0