HD 1002 A+B問題 大數相加
阿新 • • 發佈:2019-02-17
Problem DescriptionI have a very simple problem for you. Given two integers A and B, your job is to calculate the Sum of A + B.
InputThe 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.
OutputFor 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 Input2
1 2
112233445566778899 998877665544332211
Sample OutputCase 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
AuthorIgnatius.L
Sample OutputCase 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
AuthorIgnatius.L
這道題的整體思想用到了小學兩數相加的計算公式。例如 123和234相加
我們在計算時先計算個位再計算十位最後計算百位,每次相加後都會看看會不會進位會的話再接下來的計算正進行進位。通過這種思想,我們把兩個大數相加看做一個個小的數相加,逐一計算,通過用字串陣列來儲存。例如 1 2 3與4 5 6 分別代表字串1 2 3和4 5 6,先將3和6轉化為數字,求和後判斷是否進位,最後取餘數得9,再將餘數轉化成字元9存進另一個字串中,依次類推計算完為止。 |
#include<stdio.h>
#include<string.h> int main() { int n,j,i,k,m=0;//m用來判斷是否要換行。 char a[1000],b[1000],c[1000],d[1000],e[1001];//定義五個字串陣列來儲存和接收字串 scanf("%d ",&n); int s=n; while(n--) { m++; k=0; for(i=0;i<1000;i++)//給a,b,c,d都賦初值'0', { a[i]='0'; b[i]='0'; c[i]='0'; d[i]='0'; } for(i=0;i<1001;i++)//給e賦初值'0',因為e是用來儲存結果的,兩個1000位的數相加最多不超過1001位。 e[i]='0'; scanf("%s",a); scanf("%s",b); for(i=999,j=1;i>=1000-strlen(a);i--,j++)//逆序給c,d陣列賦值以符合我們加減法計算的習慣。方便後面計算。 { c[i]=a[strlen(a)-j]; } for(i=999,j=1;i>=1000-strlen(b);i--,j++) { d[i]=b[strlen(b)-j]; } int l=(1000-strlen(a))<(1000-strlen(b))?(1000-strlen(a)):(1000-strlen(b));//找到位數較多的陣列,因為是你徐賦值的所以找到下標較小的陣列。 for(i=1000;i>=l;i--)//例如:00123,01234兩個數下標最小的是第二個陣列的第二個,因為兩個數相加有可能要進位,所以多留一位出來所以用1000。 { int x=c[i-1]-48;//先將要計算的兩個字元變為數字, int y=d[i-1]-48; int sum=x+y+k;//k代表進幾位 if(sum>=10) //判斷是否進位 { k=1; sum=sum%10;//求出應存在該位置上的數字 } else { k=0; } e[i]=sum+48;//再將改數字轉化為字元存入該字串。 } printf("Case %d:\n",m); printf("%s",a);printf(" + ");printf("%s",b);printf(" = "); for(i=l;i<1001;i++) { if(i==l&&e[i]=='0')continue; printf("%c",e[i]); }printf("\n"); if(m!=s)printf("\n");//每組資料之間換行。 }return 0; }