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.
这道题其实挺简单的,我的想法是对的,但是有冗余的部分,所以记录一下。
以下是讨论区别人分享的代码
主要思想: 我觉得这个跟加法器很像。Cin是后一位的进位,sum是本位,Cout是进位,out 为本次计算所得的结果。
sum = (out+Cin)%10;
Cout = (out+Cin)/10;
遍历即可得到结果。
问题描述
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;
遍历即可得到结果。
相关文章推荐
- 43. Multiply Strings
- 43. Multiply Strings
- 43. Multiply Strings
- Leet Code 43 Multiply Strings - 字符串表示的数相乘 - Java
- 43. Multiply Strings
- 43. Multiply Strings
- 43. Multiply Strings
- 43. Multiply Strings
- LeetCode 43. Multiply Strings
- 【LeetCode】43. Multiply Strings
- 43. Multiply Strings
- 43.Multiply Strings
- 【LeetCode】C# 43、Multiply Strings
- 43. Multiply Strings
- [Leetcode 43 Multiply Strings]大数乘法,回到乘法本身的“最基础”去优化
- leetcode 43 : Multiply Strings
- [Leetcode]#43 Multiply Strings
- 43 Multiply Strings
- 43 Multiply Strings
- leetcode-43 Multiply Strings