首页 > 其他 > 详细

HDU1002 A + B Problem II 题解 高精度加法

时间:2020-01-13 23:08:05      阅读:80      评论:0      收藏:0      [点我收藏+]

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1002

题目大意:
告诉你两个整数 \(A,B\)(它们的位数均不超过 \(1000\)),求它们的和。

解题思路:
高精度加法入门题,直接用数组来模拟。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
const int maxn = 1010;
int T, n, m, a[maxn], b[maxn], c[maxn];
char s[maxn], t[maxn];
int main() {
    scanf("%d", &T);
    for (int cas = 1; cas <= T; cas ++) {
        scanf("%s%s", s, t);
        if (cas > 1) puts("");
        printf("Case %d:\n%s + %s = ", cas, s, t);
        n = strlen(s);
        m = strlen(t);
        memset(c, 0, sizeof(c));
        memset(a, 0, sizeof(a));
        memset(b, 0, sizeof(b));
        for (int i = 0; i < n; i ++) a[i] = s[n-1-i] - '0';
        for (int i = 0; i < m; i ++) b[i] = t[m-1-i] - '0';
        int len = max(n, m);
        for (int i = 0; i < len; i ++) {
            c[i] += a[i] + b[i];
            if (c[i] >= 10) {
                c[i+1] ++;
                c[i] %= 10;
            }
        }
        int i = len;
        if (!c[i]) i --;
        while (i >= 0) printf("%d", c[i--]);
        puts("");
    }
    return 0;
}

HDU1002 A + B Problem II 题解 高精度加法

原文:https://www.cnblogs.com/quanjun/p/12189654.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!