【LeetCode】43. Multiply Strings
来源:互联网 发布:备案的是域名还是主机 编辑:程序博客网 时间:2024/06/06 19:36
题目描述
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.
解题思路
大数相乘。
为了解题思路清晰,我是自己模拟手工相乘的方法做的。具体见代码注释。
AC代码
class Solution {public: //给数组左边加0,使其最终长度为tLen string leftPad(string num, int tLen) { int numLen = num.size(); string zero(tLen - numLen, '0'); return zero + num; } //大数相加。先将两个大数前面补0使其长度相同,注意最后的carry string strAdd(string num1, string num2) { int maxLen = max(num1.size(), num2.size()); num1 = leftPad(num1, maxLen); num2 = leftPad(num2, maxLen); string ans; int carry = 0; for (int idx = maxLen - 1; idx >= 0; --idx) { int curSum = (num1[idx] - '0') + (num2[idx] - '0'); curSum += carry; ans.push_back((curSum % 10) + '0'); carry = curSum / 10; } if (carry != 0) ans.push_back(carry + '0'); reverse(ans.begin(), ans.end()); return ans; } //大数相乘。每次使用一个位与另一个数字相乘,然后通过大数相加更新答案。 string multiply(string num1, string num2) { if (num2 == "0" || num1 == "0") return "0"; string ans; for (int i = num2.size() - 1; i >= 0; --i) { if (num2[i] == '0') continue; string curAns; int carry = 0; for (int j = num1.size() - 1; j >= 0; --j) { int mul = (num2[i] - '0') * (num1[j] - '0'); mul += carry; curAns.push_back((mul % 10) + '0'); carry = mul / 10; } if (carry != 0) curAns.push_back(carry + '0'); reverse(curAns.begin(), curAns.end()); string zeros(num2.size() - i - 1, '0'); ans = strAdd(ans, curAns + zeros); } return ans; }};
0 0
- [LeetCode]43.Multiply Strings
- LeetCode --- 43. Multiply Strings
- [Leetcode] 43. Multiply Strings
- [leetcode] 43.Multiply Strings
- 43. Multiply Strings LeetCode
- leetcode 43. Multiply Strings
- LeetCode 43. Multiply Strings
- LeetCode 43. Multiply Strings
- LeetCode 43. Multiply Strings
- [leetcode] 43. Multiply Strings
- Leetcode 43. Multiply Strings
- (Leetcode)43. Multiply Strings
- LeetCode - 43. Multiply Strings
- leetcode 43. Multiply Strings
- [LeetCode] 43. Multiply Strings
- leetcode 43. Multiply Strings
- Leetcode 43. Multiply Strings
- leetcode 43. Multiply Strings
- JUC-Map的选择
- 什么是android
- bzoj 1230 线段树 标签
- Why do you read so much?
- Android偏好参数SharedPreferences
- 【LeetCode】43. Multiply Strings
- MySQL解决字符乱码问题
- Android4.4屏幕录制命令screenrecord
- Unix网络编程—— shutdown与close
- <video>标签的属性
- UOJ#274 BZOJ4736 【清华集训2016】温暖会指引我们前行
- 自制图标字体
- 求素数
- ZOJ3811:Untrusted Patrol(并查集)