acm 1002 算法设计

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了acm 1002 算法设计相关的知识,希望对你有一定的参考价值。

最近突然想往算法方向走走,做了做航电acm的几道题

二话不说,开始

航电acm 1002 题主要是处理长数据的问题,算法原理比较简单,就是用字符数组代替int,因为int太短需要处理的数据较长

下面是问题描述:

Problem Description
I have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
 

 

Input
The first line of the input contains an integer T(1<=T<=20) which means the number of test cases. Then T lines follow, each line consists of two positive integers, A and B. Notice that the integers are very large, that means you should not process them by using 32-bit integer. You may assume the length of each integer will not exceed 1000.
 

 

Output
For each test case, you should output two lines. The first line is "Case #:", # means the number of the test case. The second line is the an equation "A + B = Sum", Sum means the result of A + B. Note there are some spaces int the equation. Output a blank line between two test cases.
 

 

Sample Input
2 1 2 112233445566778899 998877665544332211
 

 

Sample Output
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
 

 

Author
Ignatius.L

下面列出我的代码 参考http://blog.csdn.net/odaynot/article/details/8049632

#include<stdio.h>
#include<string.h>
 int toInt(char c){
     return c-0;
 }
 int main(){
     int i, n,j=1,al,bl,ml,t;
     char a[1000], b[1000];//存储输入的两个数
    int count[1001];       
     scanf("%d",&n);
     while(n--){
         if(j!=1)printf("\n");
         scanf("%s",a);
         al=strlen(a);//返回字符串结束符之前的字符个数 
         scanf("%s",b);
         bl=strlen(b);
         ml=(al>bl)?al:bl;//获取较长的字符长度
         t=ml;
         for(i=0;i<=ml;i++)count[i]=0;//初始化数组 
        for(ml;al>0&&bl>0;ml--){
            count[ml]+=toInt(a[--al])+toInt(b[--bl]);
             if(count[ml]/10){
                 //处理进位问题 
                 count[ml-1]++;
                 count[ml]=count[ml]%10;
             }
        }
        while(al>0){
            count[ml--]+=toInt(a[--al]);
            if(count[ml+1]/10){
                count[ml]++;
                count[ml+1]%=10;
            }
        }  
         while(bl>0){
             count[ml--]+=toInt(b[--bl]);
             if(count[ml+1]/10){
                 count[ml]++;
                 count[ml+1]%=10;
             }
         }
         
         printf("Case %d:\n%s + %s =",j++,a,b);
         for(i=0;i<=t;i++){
             if(i==0&&count[i]==0){
                 i++;
             }
             printf("%d",count[i]);
         }
         printf("\n");      
     }
     return 0;
 }

 欢迎批评,疑问请留言

以上是关于acm 1002 算法设计的主要内容,如果未能解决你的问题,请参考以下文章

大数相加(类似杭电acm1002)

GDUFE ACM-1002

GDUFE ACM-1002

ACM1002:A + B Problem II

杭电HDOJ--ACM1002(JAVA解题,运用BigInteger)

ACM程序设计报告