#Leetcode# 43. Multiply Strings
Posted 丧心病狂工科女
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了#Leetcode# 43. Multiply Strings相关的知识,希望对你有一定的参考价值。
https://leetcode.com/problems/multiply-strings/
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3" Output: "6"
Example 2:
Input: num1 = "123", num2 = "456" Output: "56088"
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
代码:
class Solution { public: string multiply(string num1, string num2) { string res; int n1 = num1.size(), n2 = num2.size(); int k = n1 + n2 - 2, carry = 0; vector<int> v(n1 + n2, 0); for (int i = 0; i < n1; ++i) { for (int j = 0; j < n2; ++j) v[k - i - j] += (num1[i] - ‘0‘) * (num2[j] - ‘0‘); } for (int i = 0; i < n1 + n2; ++i) { v[i] += carry; carry = v[i] / 10; v[i] %= 10; } int i = n1 + n2 - 1; while (v[i] == 0) --i; if (i < 0) return "0"; while (i >= 0) res.push_back(v[i--] + ‘0‘); return res; } };
大数乘法
以上是关于#Leetcode# 43. Multiply Strings的主要内容,如果未能解决你的问题,请参考以下文章
<LeetCode OJ> 43. Multiply Strings