[LeetCode] 43. Multiply Strings 字符串相乘
Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Example 1:
Input: num1 = "2", num2 = "3" Output: "6"
Example 2:
Input: num1 = "123", num2 = "456" Output: "56088"
Note:
- The length of both
num1
andnum2
is < 110. - Both
num1
andnum2
contain only digits0-9
. - Both
num1
andnum2
do not contain any leading zero, except the number 0 itself. - You must not use any built-in BigInteger library or convert the inputs to integer directly.
求两个字符串数字的相乘,输入的两个数和返回的数都是以字符串格式储存,这样做的原因可能是计算超大数相乘不受数值范围的约束。题目也要求不能用内置长整数计算。
解法:用数组来记录每一位的计算结果,最后在转成字符串就可以了。
Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | public String multiply(String num1, String num2) { int m = num1.length(), n = num2.length(); int [] pos = new int [m + n]; for ( int i = m - 1 ; i >= 0 ; i--) { for ( int j = n - 1 ; j >= 0 ; j--) { int mul = (num1.charAt(i) - '0' ) * (num2.charAt(j) - '0' ); int p1 = i + j, p2 = i + j + 1 ; int sum = mul + pos[p2]; pos[p1] += sum / 10 ; pos[p2] = (sum) % 10 ; } } StringBuilder sb = new StringBuilder(); for ( int p : pos) if (!(sb.length() == 0 && p == 0 )) sb.append(p); return sb.length() == 0 ? "0" : sb.toString(); } |
Python:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Solution( object ): def multiply( self , num1, num2): """ :type num1: str :type num2: str :rtype: str """ num1, num2 = num1[:: - 1 ], num2[:: - 1 ] res = [ 0 ] * ( len (num1) + len (num2)) for i in xrange ( len (num1)): for j in xrange ( len (num2)): res[i + j] + = int (num1[i]) * int (num2[j]) res[i + j + 1 ] + = res[i + j] / 10 res[i + j] % = 10 # Skip leading 0s. i = len (res) - 1 while i > 0 and res[i] = = 0 : i - = 1 return ''.join( map ( str , res[i:: - 1 ])) |
C++:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | class Solution { public : string multiply(string num1, string num2) { string res; int n1 = num1.size(), n2 = num2.size(); int k = n1 + n2 - 2, carry = 0; vector< int > v(n1 + n2, 0); for ( int i = 0; i < n1; ++i) { for ( int j = 0; j < n2; ++j) { v[k - i - j] += (num1[i] - '0' ) * (num2[j] - '0' ); } } for ( int i = 0; i < n1 + n2; ++i) { v[i] += carry; carry = v[i] / 10; v[i] %= 10; } int i = n1 + n2 - 1; while (v[i] == 0) --i; if (i < 0) return "0" ; while (i >= 0) res.push_back(v[i--] + '0' ); return res; } }; |
All LeetCode Questions List 题目汇总
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构