26 Feb 2019

LeetCode-43 Multiply Strings

LeetCode-43: Multiply Strings

链接:https://leetcode.com/problems/multiply-strings/

题解

OJ​好鬼畜啊

大数乘法板子题

结果需要转化为$string$型不然会$RE$

$Divide\;and\;conquer$(分治法)​

将每一位算出来,最后进行进位和反转即可

//Time: 8ms Memory: 10.6MB
class Solution {
public:
	string multiply(string num1, string num2) {
		int len1 = num1.length(), len2 = num2.length(), len = 0;
		int maxn = 110;
		int a[maxn] = {0}, b[maxn] = {0}, c[2 * maxn] = {0};
		char res[maxn * 2];
		for(int j = 0, i = len1 - 1; i >= 0; --i) a[j++] = num1[i] - '0';
		for(int j = 0, i = len2 - 1; i >= 0; --i) b[j++] = num2[i] - '0';
		for(int i = 0; i < len2; ++i)
			for(int j = 0; j < len1; ++j)
				c[i + j] += a[j] * b[i];
		for(int i = 0; i < 2 * maxn; ++i)
			if(c[i] >= 10) c[i + 1] += c[i] / 10, c[i] %= 10;
		for(int i = 0; i < 2 * maxn; ++i) res[i] = (char)(c[i] + '0');
		for(int i = 2 * maxn - 1; i > 0; --i)
			if(res[i] == '0') res[i] = '\0';
			else break;
		for(int i = 0; i < 2 * maxn; ++i)
			if(res[i] != '\0') ++len;
			else break;
		reverse(res, res + len);
		string ans(res);
		return ans;
	}
};

Tags:
0 comments