Multiply Strings 发表于 2017-06-08 | 分类于 算法 Multiply Strings题目描述: 给定两个代表数字的字符串,要求计算其乘积的结果,返回其字符串形式。 例子: 具体描述见LeetCode43 解题思路: 代码如下:123456789101112131415161718192021222324252627282930313233343536class Solution {public: string multiply(string num1, string num2) { if (num1 == "0" || num2 == "0") return "0"; //如果乘数中有任意一个是0的情况下直接返回0即可 reverse(num1.begin(), num1.end()); reverse(num2.begin(), num2.end()); //逆序字符串从低位开始处理 int carry =0; int step = 0; string res = ""; for (int i = 0; i < num1.size(); i++){ int position = step; for (int j = 0; j < num2.size(); j++){ int num = (num1[i] - '0') * (num2[j] - '0') + carry; if (position < res.size()){ num += res[position] - '0'; res[position] = num % 10 + '0'; }else{ res.append(1, (num % 10) + '0'); } carry = num / 10; position++; } if (carry > 0){ res.append(1, carry + '0'); } step++; carry = 0; } reverse(res.begin(), res.end()); return res; }};