面试常考 大数加减乘除

大数乘法

#include <bits/stdc++.h>
using namespace std;


vector<int> mul(string s1, string s2) {
    int l1 = s1.size();
    int l2 = s2.size();
    vector<int> res(l1+l2, 0);
    for(int i=0; i<l1; i++) {
        for(int j=0; j<l2; j++) {
            res[i+j+1] += (s1[i]-'0')*(s2[j]-'0');
        }
    }
    // int i = res.size() -1;
    for(int i=l1+l2-1; i>0; i--) {
        res[i-1] += res[i]/10;
        res[i] %= 10;
    }
    // 去除前导0就可以了
    return v;
}

int main() {
    string s1 = "99";
    string s2 = "99";
    vector<int> v = mul(s1, s2);
    int i =0;
    while(i < v.size() && v[i] == 0) i++;
    for( ; i<v.size(); i++) {
        cout<<v[i];
    }cout<<endl;
    return 0;
}
posted @ 2019-08-20 10:26 Draymonder 阅读(...) 评论(...) 编辑 收藏