leetcode 415.字符串相加

#define MAX 10000
class MyInt{
private:
    int _n;
    int *_arr;
public:
    MyInt();
    MyInt(string s);               // 支持从字符串创建
    friend MyInt operator+(MyInt const &mi1, MyInt const  &mi2);
    string toString();
    friend void print(MyInt mi);
    ~MyInt();
};
MyInt::MyInt(){
    _n=0; 
    _arr = new int[MAX];
}

// 倒着存
MyInt::MyInt(string s){
    _n = s.length();
    _arr = new int[MAX];
    for(int i=0; i<_n; i++)
        _arr[i] = s[_n-1-i]-'0';
}

MyInt operator+(MyInt const &mi1, MyInt const  &mi2){
    MyInt mi3;
    int i1=0, i2=0, i3=0;
    bool c = false; // 进位标志
    while(i1<mi1._n || i2<mi2._n){
        int k1 = i1<mi1._n?mi1._arr[i1]:0;
        int k2 = i2<mi2._n?mi2._arr[i2]:0;
        int t = k1+k2+c;
        if(t >= 10){
            t %= 10;
            c = true;
        }
        else c = false;
        mi3._arr[i3] = t;
        i1++; i2++; i3++;
    }
    mi3._arr[i3]=c;
    mi3._n = i3+c;
    return mi3;
}

string MyInt::toString(){
    string s;
    for(int i=0; i<_n; i++)
        s += _arr[_n-1-i]+'0';
    return s;
}

void print(MyInt mi){
    for(int i=0; i<mi._n; i++) 
        cout<<mi._arr[mi._n-1-i];
}

MyInt::~MyInt(){
    delete[] _arr;
}
class Solution {
public:
    string addStrings(string num1, string num2) {
        MyInt mi1(num1);
        MyInt mi2(num2);
        MyInt mi3 = mi1 + mi2;
        return mi3.toString();
    }
};

给定两个字符串形式的非负整数 num1 和num2 ,计算它们的和。

注意:

num1 和num2 的长度都小于 5100.
num1 和num2 都只包含数字 0-9.
num1 和num2 都不包含任何前导零。
你不能使用任何內建 BigInteger 库, 也不能直接将输入的字符串转换为整数形式。

这我用上了之前制作的大整数类,真爽。
 

发布了147 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/HeroIsUseless/article/details/103747107