Commits

liangsdu committed 0937c68

模拟大数相加,可以考虑把功能分散到函数里,这样可读性好一点。另注意最后的格式

Comments (0)

Files changed (1)

+/** HDOJ 1002: A + B problem II **/
+#include <stdio.h>
+#include <string.h>
+#define NUM 1001
+
+int main()
+{
+    int m,n;
+
+
+    char a[NUM],b[NUM], sum[NUM];
+
+    scanf("%d",&n);
+    for(m=1; m<=n; m++)
+    {
+        scanf("%s %s", a,b);
+        int la = strlen(a);
+        int  lb = strlen(b);
+
+        int  i=la-1;
+        int  j=lb-1;
+        int k=0;
+        int tag=0;
+        while(i>=0 && j>=0)
+        {
+            sum[k]  = (a[i] - '0' + b[j] - '0' + tag) % 10 + '0';
+            tag = (a[i] - '0' + b[j] - '0' + tag) / 10;
+            i--, j--, k++;
+        }
+        while(i >= 0)
+        {
+            sum[k]  = (a[i] - '0' + tag) % 10 + '0';
+            tag = (a[i] - '0' + tag) / 10;
+            i--, k++;
+        }
+        while(j >= 0)
+        {
+            sum[k]  = ( b[j] - '0' + tag) % 10 + '0';
+            tag = ( b[j] - '0' + tag) / 10;
+            j--, k++;
+        }
+        if(tag == 1) sum[k++] = '1';      /*最高位进位*/
+        sum[k]='\0';
+
+        printf("Case %d:\n", m);
+        printf("%s + %s = ", a, b);
+        for(k=k-1; k>=0; k--)
+            printf("%c", sum[k]);
+        printf("\n");
+        if(m < n)
+            printf("\n");
+    }
+
+    return 0;
+}