【LeetCode】43. Multiply Strings
LeetCode 43 strings
2023-09-11 14:20:27 时间
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.
class Solution { public: string multiply(string num1, string num2) { int n1 = num1.size(); int n2 = num2.size(); vector<int> result(n1+n2); string resultStr; for(int i = n1-1; i >= 0; i --) {// for num1[i] int carry = 0; int val1 = num1[i] - '0'; for(int j = n2-1; j >= 0; j --) {// for num2[j] int val2 = num2[j] - '0'; int res = val1 * val2; int ind = (n1-1-i)+(n2-1-j); result[ind] += carry; result[ind] += res; carry = result[ind] / 10; result[ind] %= 10; } if(carry != 0) { int ind = (n1-1-i)+n2; result[ind] += carry; } } //reverse result reverse(result.begin(), result.end()); int i; for(i = 0; i < n1+n2; i ++) { if(result[i] != 0) break; } if(i == n1+n2) //all 0 return "0"; else { for(; i < n1+n2; i ++) { resultStr += (result[i] + '0'); } return resultStr; } } };
相关文章
- Java实现 LeetCode 717 1比特与2比特字符(暴力)
- Java实现 LeetCode 705 设计哈希集合(使用数组保存有没有被用过)
- SQL Server实现 LeetCode 176 第二高的薪水
- Java实现 LeetCode 153 寻找旋转排序数组中的最小值
- Java实现 LeetCode 135 分发糖果
- Java实现 LeetCode 74 搜索二维矩阵
- Java实现 LeetCode 64 最小路径和
- Java实现 LeetCode 43 字符串相乘
- (LeetCode 82)Remove Duplicates from Sorted List II
- 【数组&双指针】LeetCode 1. 两数之和【简单】
- LeetCode(82):删除排序链表中的重复元素 II
- 每日一道 LeetCode (43):翻转二进制数
- 每日一道 LeetCode (12):最大子序和
- LeetCode(70): 爬楼梯
- Python 刷Leetcode题库,顺带学英语单词(43)
- leetcode 37. 解数独----回溯篇1
- [LeetCode]Median of Two Sorted Arrays 二分查找两个有序数组的第k数(中位数)
- Leetcode 1464. 数组中两元素的最大乘积
- [LeetCode] 152. 乘积最大子数组 ☆☆☆(动态规划)
- [LeetCode] 109. 有序链表转换二叉搜索树 ☆☆☆(递归)
- [LeetCode] 43. Multiply Strings ☆☆☆(字符串相乘)
- 【Mac系统】Vscode使用LeetCode插件报错‘leetcode.toggleLeetCodeCn‘ not found
- 【Leetcode刷题Python】LeetCode 478. 在圆内随机生成点