四则运算:*

重载运算符

#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct BigInt {
    vector<int> v;
    static const int BASE = 10000;
    static const int WIDTH = 4;
    BigInt(long long x) {
        do {
            v.push_back(x % BASE);
        }while (x /= BASE);
    }
    BigInt(string str) {
        int size = str.length();
        v.reserve(size);
        for(int i = size - 1; i >= 0; i-=WIDTH){
            string sub;
            if(i-WIDTH + 1<0)sub = str.substr(0,i+1);
            else sub = str.substr(i - WIDTH +1,WIDTH);
            int temp = atoi(sub.c_str());
            v.push_back(temp);
        }
    }
    BigInt() {
        
    }
    void removePreZero() {
        while(v.size() >= 1 && v.back() == 0) v.pop_back();
    }
    bool operator<(const BigInt &a) const {
        if (v.size() != a.v.size()) {
            return v.size() < a.v.size();
        }
        for (int i = v.size() - 1; i >= 0; i--) {
            if (v[i] != a.v[i]) {
                return v[i] < a.v[i];
            }
        }
        return false;
    }
    BigInt operator*(const BigInt &a) const {
        BigInt ans;
        ans.v.resize(v.size() + a.v.size(), 0);
        for (int i = 0; i < v.size(); i++) {
            for (int j = 0; j < a.v.size(); j++) {
                ans.v[i + j] += v[i] * a.v[j];
                ans.v[i + j + 1] += ans.v[i + j] / BASE;
                ans.v[i + j] %= BASE;
            }
        }
        ans.removePreZero();
        return ans;
    }
/*    BigInt operator*=(const BigInt &a) const {
        return *this = *this * a;
    }
*/ 
    void print(){
        if(v.size()==0)printf("0");
        for(int i = v.size() - 1 ; i >= 0 ; i--){
            if(i!=v.size()-1){
                if(v[i]<10)printf("000");
                else if(v[i]<100)printf("00");
                else if(v[i]<1000)printf("0");
            }
            printf("%d",v[i]);
        }
    }
};

int main() 
{
    BigInt a,b,ans;
    string al,bl;
    cin>>al>>bl;
    a=al,b=bl;
    ans=a*b;
    ans.print();
}

猜你喜欢

转载自www.cnblogs.com/qseer/p/9838516.html