【LeetCode】43. Multiply Strings(C++)

地址: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 and num2 is < 110.
  • Both num1 and num2 contain only digits 0-9.
  • Both num1 and num2 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.

理解:

应该是一道很经典的题了,有个大概思路,因为涉及到进位,肯定要从后往前来算,但是具体的还是很难自己实现。。还是看看别人的代码学习好啦!

实现:

来源:Brief C++ solution using only strings and without reversal
这种实现简直不能更巧妙。
总结一下里面的点:

  • 首先是结果字符串的长度,可以这样考虑。用num1的每一位去乘num2,得到一个数。然后用前一位乘num2,得到另一个,但是需要把第二个数乘10和第一个数相加。
  • 用一位数乘num2,得到的结果的长度最多就是num2的长度加一,因为一位数肯定小于10,而乘十的长度才加一。设num1的长度为mnum2n,这样每一位的结果长度最多为 n + 1 n+1 。其中首位放的就是进位。
    在这里插入图片描述
  • m==1时,长为 n + 1 n+1 m==2,为 n + 2 n+2 ,所以结果串长度最多为 m + n m+n
  • 对于num1[i]num2[j],相乘结果在res[i+j+1]。(考虑num1[m-1]*num2[n-1],结果的最后一位为res[m+n-1])。
  • num1[i]乘完num2后,最后可能还有进位,这个进位应该是放在结果(n+1位数)的第一位,也就是sum[i](同样考虑i=m-1,结果应该放在n+1位,res最后一位是m+n-1,从m-1到m+n-1是n+1位)
  • 在这里插入图片描述
class Solution {
public:
	string multiply(string num1, string num2) {
		string res(num1.size() + num2.size(), '0');
		for (int i = num1.size() - 1; i >= 0; --i) {
			int carry = 0;
			for (int j = num2.size() - 1; j >= 0; --j) {
				int tmp = (res[i + j + 1] - '0') + (num2[j] - '0')*(num1[i] - '0') + carry;
				res[i + j + 1] = tmp % 10 + '0';
				carry = tmp / 10;
			}
			res[i] += carry;
		}
		auto pos = res.find_first_not_of('0');
		if (pos == string::npos)
			return "0";
		return res.substr(pos, res.length() - pos);
	}
};

猜你喜欢

转载自blog.csdn.net/Ethan95/article/details/84592751