重载运算符,c++,求改

P1001 A+B Problem

niumiao123 @ 2024-07-16 16:56:56

算不了负数,代码如下

#include<bits/stdc++.h>
using namespace std;
int mx;
const int N = 1e3 + 50;
struct BigNum
{
    int a[N], len;
    void init()
    {
        len = 0;
        memset(a,0,sizeof a);
    }
    BigNum operator + (BigNum b)
    {
        BigNum c; c.init();
        mx=max(len,b.len);
        for(int i = 0;i < mx; ++ i){
            c.a[i]=a[i]+b.a[i];
            c.a[i + 1] += c.a[i] / 10;
            c.a[i] %= 10;
        }
        return c;
    }
    void print()
    {
        int u=1;
        for(int i = mx+1;i >= 0; -- i){
            if(a[i]!=0){
                u=0;
            } 
            if(u==0){
            cout<<a[i];
            }
        }
    }
}x; 
string s,s1;
int main()
{   
    std::ios::sync_with_stdio(false);
    cin >> s >> s1;
    if(s[0]=='0'&&s1[0]=='0'){
        cout<<0;
        return 0;
    }
    BigNum x,y,c; 
    x.init();y.init();
    x.len = s.size();
    y.len = s1.size();
    for(int i = 0;i < x.len;++ i)
        x.a[i] = s[s.size()-1-i] - '0';
    for(int i = 0;i < y.len;++ i)
        y.a[i] = s1[s1.size()-1-i] - '0';
    (x+y).print();
    return 0;
}

by zjf2023 @ 2024-08-01 23:07:05

@huangboran 你说的很对,但是请注意《洛谷讨论区规范》(虽然我也是)


上一页 |