大整数减法 模板

本文介绍了一种使用C++实现的大数减法算法。该算法通过字符串来处理任意大小的整数运算,并实现了借位操作。代码中详细展示了如何逐位进行比较和相减的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <cstdio>
#include <cstring>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

string sub(string a, string b) {
        int i, j, k, s, flag = 1;
        int tmpa[10000], tmpb[10000], c[10000];
        string ans;
        if (a.size() < b.size() || (a.size() == b.size() && a.compare(b) < 0)) {
                string tmp = a;
                a = b;
                b = tmp;
                flag = 0;
        }
        while (a.length() > b.length()) b = '0' + b;
        int len = a.length();
        for (i = 0; i < len; i ++) {
                tmpa[i] = a[i] - '0';
                tmpb[i] = b[i] - '0';
        }
        for (i = len - 1; i >= 0; i --) {
                if (tmpa[i] >= tmpb[i]) {
                        c[i] = tmpa[i] - tmpb[i];
                } else {
                        c[i] = 10 + tmpa[i] - tmpb[i];
                        tmpa[i - 1] --;
                }
        }
        for (i = 0; i < len - 1; i ++) {
                if (c[i] != 0) break;
        }
        for (j = i; j < len; j ++) {
                ans += (char)(c[j] + '0');
        }
        if (!flag) ans = '-' + ans;
        return ans;
}
int main()
{
        string a, b;
        while (cin >> a >> b) {
                cout << sub(a, b) << endl;
        }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值