43. Multiply Strings

    xiaoxiao2025-01-14  15

    题目链接:https://leetcode.com/problems/multiply-strings/

    代码一

    class Solution: def multiply(self, num1: str, num2: str) -> str: result=0 for i in range(len(num1)): tmp=0 for j in range(len(num2)): tmp=tmp*10+(ord(num2[j])-ord('0'))*(ord(num1[i])-ord('0')) result=result*10+tmp return str(result)

    拆开相乘,然后相加

    代码二

    class Solution: def multiply(self, num1: str, num2: str) -> str: return str(self.toInt(num1)*self.toInt(num2)) # 转为整数 def toInt(self,num): result=0 for i in range(len(num)): result=result*10+(ord(num[i])-ord('0')) return result

    这个思路有点投机取巧,先分别转为整数,在相乘,然后转为字符串

    策略

    ord函数,通过ASCII码进行转换 ord(num[i])-ord(‘0’)

    最新回复(0)