惯看花开花又谢,却怕缘起缘又灭…….成为你的护身符 shuangjian_wei@qq.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;
 }

 欢迎批评,疑问请留言

posted @ 2016-02-03 17:35  护身符  阅读(380)  评论(0编辑  收藏  举报
宝剑锋从磨砺出 梅花香自苦寒来!
联系我: shuangjian_wei@qq.com