Leetcode43. 字符串相乘

题目

给定两个以字符串形式表示的非负整数 num1 和 num2,返回 num1 和 num2 的乘积,它们的乘积也表示为字符串形式。

示例 1:

输入: num1 = "2", num2 = "3"
输出: "6"

示例 2:

输入: num1 = "123", num2 = "456"
输出: "56088"

说明:

num1 和 num2 的长度小于110。
num1 和 num2 只包含数字 0-9。
num1 和 num2 均不以零开头,除非是数字 0 本身。
不能使用任何标准库的大数类型(比如 BigInteger)或直接将输入转换为整数来处理。

C++解法

#include 
#include 
#include 
#include 
using namespace std;
class Solution {
public:
    string multiply(string num1, string num2) {
        long length = num1.size() + num2.size() - 1;
        vector lhs, rhs, result(length, 0);
        string number;
        for (auto item: num1) lhs.push_back(item - '0');
        for (auto item: num2) rhs.push_back(item - '0');
        int flag = 0;
        for (int i = 0; i < lhs.size(); i++) {
            for (int j = 0; j < rhs.size(); j++) {
                int result_index = (int)result.size() - i - j - 1;
                int value =  (lhs[lhs.size() - i - 1]) * (rhs[rhs.size() - j - 1]) + (result[result_index]) + flag;
                flag = value / 10;
                result[result_index] = (value % 10);
            }
            if (flag > 0) {
                int result_index = (int)result.size() - i - (int)rhs.size() - 1;
                if (result_index < 0) {
                    result.insert(result.begin(), flag);
                    flag = 0;
                } else {
                    int value = result[result_index] + flag;
                    flag = value / 10;
                    result[result_index] = (value % 10);
                }
            }
        }
        bool noneZero = false;
        for (int i = 0; i < result.size(); i++) {
            int item = result[i];
            if (item > 0) noneZero = true;
            if (noneZero == true || i == result.size() - 1) number.push_back('0' + item);
        }
        return number;
    }
};

int main(int argc, const char * argv[]) {
    // insert code here...
    Solution solution;
    cout << solution.multiply("99", "99") << endl;
    cout << solution.multiply("99", "9") << endl;
    cout << solution.multiply("123", "456") << endl;
    cout << solution.multiply("0", "999999") << endl;
    return 0;
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/multiply-strings

你可能感兴趣的:(Leetcode43. 字符串相乘)