您的位置:首页 > 编程语言 > Go语言

43. Multiply Strings

2017-03-06 21:48 423 查看
问题来自leetcode

问题描述

Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.

Note:

The length of both num1 and num2 is < 110.

Both num1 and num2 contains only digits 0-9.

Both num1 and num2 does not contain any leading zero.

You must not use any built-in BigInteger library or convert the inputs to integer directly.

这道题其实挺简单的,我的想法是对的,但是有冗余的部分,所以记录一下。

以下是讨论区别人分享的代码

string sum(num1.size() + num2.size(), '0');

for (int i = num1.size() - 1; 0 <= i; --i) {
int carry = 0;
for (int j = num2.size() - 1; 0 <= j; --j) {
int tmp = (sum[i + j + 1] - '0') + (num1[i] - '0') * (num2[j] - '0') + carry;
sum[i + j + 1] = tmp % 10 + '0';
carry = tmp / 10;
}
sum[i] += carry;
}

size_t startpos = sum.find_first_not_of("0");
if (string::npos != startpos) {
return sum.substr(startpos);
}
return "0";


主要思想: 我觉得这个跟加法器很像。Cin是后一位的进位,sum是本位,Cout是进位,out 为本次计算所得的结果。

sum = (out+Cin)%10;

Cout = (out+Cin)/10;

遍历即可得到结果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode algorithm