lc 字符串相乘

链接:https://leetcode-cn.com/explore/interview/card/bytedance/242/string/1015/

代码:

#include <iostream>
#include <algorithm>
using namespace std;

class Solution {
public:
    string multiply(string num1, string num2) {
        // cout <<  to_string(34) << endl;
        // string str = "34";
        // cout << stoi(str) << endl;
        if(num1 == "" || num2 == "") return "";
        if(num1 == "0" || num2 == "0") return "0";
        int len1 = num1.size();
        int len2 = num2.size();
        string temp_s1 = num1;
        string res = "0";
        for(int i = len2-1; i >= 0; i--) {
            int temp = int(num2[i]) - 48;
            while(temp--) {
                res = add(res, temp_s1);
                res = normalize(res);
            }
            temp_s1 += "0";
        }
        return res;
    }
    string add(string num1, string num2) {
        int len1 = num1.size();
        int len2 = num2.size();
        int len = max(len1, len2);
        string s1 = add_zero(num1, len+1);
        string s2 = add_zero(num2, len+1);
        // cout << s1 << " " << s2 << endl;
        string res = "";
        for(int i = len; i >= 0; i--) {
            res += "0";
        }
        // cout << res << endl;
        int carry[500] = {0};
        for(int i = len; i >= 0; i--) {
            int n1 = int(s1[i])-48;
            int n2 = int(s2[i])-48;
            // cout << n1 << " " << n2 << endl;
            if(carry[i] + n1 + n2 < 10) {
                res[i] = char(carry[i]+n1+n2+48);
            }
            else {
                // res[0] < 1 so i-1 is valid
                // cout << i << endl;
                carry[i-1] = 1;
                res[i] = char((carry[i]+n1+n2) % 10 + 48);
            }
        }
        // cout << res << endl;
        return res;
    }
    string add_zero(string num, int len) {
        int len_num = num.size();
        int loop = len - len_num;
        string res = "";
        while(loop--) {
            res += "0";
        }
        res += num;
        return res;
    }
    string normalize(string num) {
        if(num.size() == 1) return num;
        if(num[0] != '0') return num;
        else {
            string res = "";
            for(int i = 1; i < num.size(); i++) {
                res += num[i];
            }
            return res;
        }
    }
};
View Code

思路:normalize掉有前置 0 的,乘法不过是特殊的加法,模拟就好,将短长 string 都补齐到 max_len+1的长度,再设置数组 carry 考虑进位问题。

posted on 2020-05-18 00:08  FriskyPuppy  阅读(242)  评论(0编辑  收藏  举报

导航