zoukankan      html  css  js  c++  java
  • 1005 大数加法

    基准时间限制:1 秒 空间限制:131072 KB  

    给出2个大整数A,B,计算A+B的结果。

    Input

    第1行:大数A 第2行:大数B (A,B的长度 <= 10000 需注意:A B有可能为负数)

    Output

    输出A + B

    Input示例

    68932147586 468711654886

    Output示例

    537643802472

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <string.h>
     4 
     5 char A[10005];
     6 char B[10005];
     7 int fa, fb; 
     8 
     9 void swap(char* a, int i, int j)
    10 {
    11     char t = a[i] - '0';
    12     a[i] = a[j] - '0';
    13     a[j] = t;
    14 }
    15 
    16 void add(char* a, char* b)
    17 {
    18     int la, lb, i, j, s, l, c=0;
    19     la = strlen(a);
    20     lb = strlen(b);
    21     
    22     for (i = fa, j = la-1; i <= j; ++i, --j) swap(a, i, j);
    23     for (i = fb, j = lb-1; i <= j; ++i, --j) swap(b, i, j);
    24     
    25     for (i = fa; i<la || i<lb; ++i) {
    26         s = a[i] + b[i] + c;
    27         c = s / 10;
    28         a[i] = s % 10;
    29     }
    30     a[i] = c;
    31     l = c ? i : i-1;
    32     if (fa) printf("-");
    33     for (i = l; i >= fa; --i) printf("%d", a[i]);
    34 }
    35 
    36 int cmp(char* a, char* b)
    37 {
    38     int i;
    39     int la = strlen(a);
    40     int lb = strlen(b);
    41     
    42     if (la-fa > lb-fb)
    43         return 1;
    44     else if (la-fa < lb-fb)
    45             return 0;
    46     else {
    47         for (i = 0; i < la && a[i+fa]==b[i+fb]; ++i);
    48         return a[i+fa] > b[i+fb];
    49     }
    50 }
    51 
    52 void minus(char* a, char* b)
    53 {
    54     char* tmp;
    55     int la, lb, i, j, s, l, t, c=0;
    56     
    57     if (!cmp(a, b)) {
    58         tmp = a; a = b; b = tmp;
    59         t = fa; fa = fb; fb = t;
    60     }
    61     la = strlen(a);
    62     lb = strlen(b);
    63     for (i = fa, j = la-1; i <= j; ++i, --j) swap(a, i, j);
    64     for (i = fb, j = lb-1; i <= j; ++i, --j) swap(b, i, j);
    65     l = -1;
    66     for (i = 0; i+fa < la; ++i) {
    67         s = a[i+fa] - b[i+fb] - c >= 0 ? 0 : 1;
    68         a[i+fa] = (a[i+fa] - b[i+fb] - c + 10) % 10;
    69         l = a[i+fa] ? i+fa : l;
    70         c = s;
    71     }
    72     if (l < 0) printf("0");
    73     else {
    74         if (fa) printf("-");
    75         for (i = l; i >= fa; --i) printf("%d", a[i]);
    76     }
    77 }
    78 
    79 int main ()
    80 {
    81     scanf("%s%s", A, B);
    82     fa = ('-' == A[0]);
    83     fb = ('-' == B[0]);
    84     if (fa^fb)
    85         minus(A, B);
    86     else
    87         add(A, B);
    88     return 0;
    89 }
  • 相关阅读:
    CentOS 7/8修改系统运行级别
    Sketchup 汇总
    [转]Ruby之类的真相
    [转]Ruby之代码块的迷思
    [转]ruby中的异常处理
    [转]ruby中Class的allocate
    [转]ruby中require和load的区别
    [转]ruby之方法查找
    [转]ruby之动态方法
    [转] ruby之对象体系
  • 原文地址:https://www.cnblogs.com/clairvoyant/p/5626917.html
Copyright © 2011-2022 走看看