leetcode: Multiply Strings
http://oj.leetcode.com/problems/multiply-strings/
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.
思路:
这是一道经常出现的面试题。竖式乘法怎么做的照搬就可以,注意看代码,用一个string搞定。
class Solution { public: string multiply(string num1, string num2) { reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); if (("0" == num1) || ("0" == num2)) { return "0"; } string result = ""; int i, j; int flag = 0, steps = 0; for (int i = 0; i < num1.length(); ++i) { int position = steps; for (int j = 0; j < num2.length(); ++j) { int v = (num1[i] - '0') * (num2[j] - '0') + flag; if (position < result.length()) { v += result[position] - '0'; result[position] = (v % 10) + '0'; } else { result.append(1, (v % 10) + '0'); } flag = v / 10; ++position; } if (flag > 0) { result.append(1, flag + '0'); } flag = 0; ++steps; } reverse(result.begin(), result.end()); return result; } };