重载运算符,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 zhizhenhuyuzhe @ 2024-07-16 17:01:38

聰明人從來都不這麽算,看題解不得了


by __F__ @ 2024-07-16 17:05:13

@niumiao123 牛淼是你吗


by fire_flies @ 2024-07-16 17:08:25

@yuhan09 我是牛淼


by huangboran @ 2024-07-16 19:00:04

@niumiao123 直接a+b不就可以了吗


by niumiao123 @ 2024-07-16 19:15:53

@huangboran ,教练教的,想强化一下


by huangboran @ 2024-07-16 19:17:02

@niumiao123 哦


by huangboran @ 2024-07-16 19:50:31

@niumiao123 我发现在座的各位都是2次元


by _joker_r @ 2024-07-21 08:18:39

不是,哥们 @niumiao123 @fire_flies


by niumiao123 @ 2024-07-21 08:45:57

@_joker_r ?


by SwethessPotion @ 2024-07-23 15:35:51

特判一下符号:

if (s[0] == "-" ^ s1[0] == "-")
{
    cout << "-";
}

| 下一页