43. Multiply Strings

来源:互联网 发布:家用网络交换机 编辑:程序博客网 时间:2024/06/05 12:34

先上题目:

Given two numbers represented as strings, return multiplication of the numbers as a string.

Note:

  • The numbers can be arbitrarily large and are non-negative.
  • Converting the input string to integer is NOT allowed.
  • You should NOT use internal library such as BigInteger.
这道题目跟老师上课讲分治的时候的例子很相似,但这道题是以字符串的形式进行乘法,按道理应该也可以运用分治去解题,但总觉得过程略显麻烦,就先按照普通逐位乘法再相加的思路写了= =。


加上题目本身给的2个字符串,一共用了4个字符串,res是用来储存最后结果的,而mul是用来储存每一次乘法得到的结果,plus1和plus2表示进位,每次得到一个mul之后,就加到res的相应位置,最终得到一个反过来的字符串,最后再反转以下就得到答案了。

isNeg1和isNeg2本来是为了区分正负数用的,然而只能怪自己没看清题目_(:з」∠)_


class Solution {public:string multiply(string num1, string num2) {string res = "0";int resIdx = 0, l1 = num1.size(), l2 = num2.size();bool isNeg1 = (num1[0] == '-'),isNeg2 = (num2[0] == '-');for (int i = l2 - 1; i >= 0; i--) {if (i == 0 && isNeg2) break;int plus1 = 0;string mul;for (int j = l1 - 1; j >= 0; j--) {if (j == 0 && isNeg1) break;int m = (num1[j] - '0') * (num2[i] - '0');m += plus1;plus1 = m / 10;m %= 10;;mul.append(1, m + '0');}if (plus1 != 0) mul.append(1, plus1 + '0');int plus2 = 0;for (int k = 0; k < mul.size(); k++) {if ((k + resIdx) > (res.size() - 1)) res.append("0");int tmp = (res[k + resIdx] - '0') + (mul[k] - '0');tmp += plus2;plus2 = tmp / 10;tmp %= 10;res[k + resIdx] = tmp + '0';}if (plus2 != 0) res.append(1, plus2 + '0');resIdx++;}if (isNeg1 ^ isNeg2 == 1) res.append("-");int l3 = res.size();for (int i = 0; i <= (l3 - 1) / 2; i++) {char ctmp = res[i];res[i] = res[l3 - i - 1];res[l3 - i - 1] = ctmp;}if (num1 == "0" || num2 == "0") res = "0";return res;}};




0 0
原创粉丝点击