洛谷高精度加法的3种解决方法

P1601 A+B Problem(高精) - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

方法1:

python

a = input()
b = input()
print(int(a)+int(b))

方法2:

java

import java.util.Scanner;
import java.math.BigInteger;
public class Main {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        BigInteger a = scan.nextBigInteger();
        BigInteger b = scan.nextBigInteger();
        BigInteger sum = a.add(b);
        System.out.println(sum);
    }
}

方法三:高精度--c++

中间wa了一次,没有判断i的范围,导致段错误。注意判断范围即:i < a.size()..... i < b.size()

#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef double db;
typedef long double ldb;
typedef pair<int, int> pii;
typedef pair<ll, ll> PII;
#define pb emplace_back
//#define int ll
#define all(a) a.begin(),a.end()
#define x first
#define y second
#define ps push_back
#define endl '\n'
#define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#define ve vector<ll>

void solve();

const int N = 1e6 + 10;
ve a,b,c;

signed main() {
    IOS;
    solve();
    return 0;
}

void solve() {
    string s1,s2;
    cin >> s1 >> s2;
    for(int i = s1.size() - 1; ~ i; -- i) a.pb(s1[i] - '0');
    for(int i = s2.size() - 1; ~ i; -- i) b.pb(s2[i] - '0');

    ll sum = 0;
    for(int i = 0; i <= max(a.size(),b.size()) + 1; ++ i)
    {
        if(i < a.size()) sum += a[i];
        if(i < b.size()) sum += b[i];
        c.pb(sum % 10);
        sum /= 10;
    }

    while(c.size() > 1 && c.back() == 0) c.pop_back();

    for(int i = c.size() - 1; ~ i; -- i) cout << c[i];
    cout << endl;



}

  • 13
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值