https://leetcode.com/problems/multiply-strings/
来源:互联网 发布:网络协议的作用和功能 编辑:程序博客网 时间:2024/06/04 19:51
https://leetcode.com/problems/multiply-strings/
因为数字很大 不能进行普通乘法
想到用分解乘法的步骤
长串和单位数字的乘法 就是 按位做乘法
积+进位%10=得数
积+进位/10=进位
最后在单独把最后一次的进位放在最前面
singlemul()就做了这件事
——————————————————
然后得到每一次的乘积之后,按位做加法
和+进位%10=得数
和+进位/10=进位
最后再把进位放在最前面
——————————————————
最最后处理串前面多余的0即可
问题是 有的case会超时
我发现 当位数比较多的时候 假设1已经乘过一遍了 可能还会再乘很多遍
因此把 0-9和数的乘积都放在modul[]里 需要拿出来用,不用再算
应该还有更好的方法
class Solution: # @param {string} num1 # @param {string} num2 # @return {string} def singlemul(self,m,k): #m is the number k is a digit sol='' up=0 for i in m[::-1]: single=(int(i)*int(k)+up)%10 up=(int(i)*int(k)+up)/10 sol=str(single)+sol sol=str(up)+sol return sol def multiply(self, num1, num2): #拆n #单独计算每一位 然后组成字符串 if len(num1)>len(num1): n=num1 m=num2 else: m=num1 n=num2 sol=['']*len(n) modul=['']*10 for i in range(10): modul[i]=Solution().singlemul(m,i) for i in range(len(n))[::-1]: sol[i]=modul[int(n[i])]+'0'*(len(n)-1-i) maxlength=len(sol[0]) for i in range(len(sol)): sol[i]=(maxlength-len(sol[i]))*'0'+sol[i] #此时sol各项已经位数相同(maxlength位) 加和即可 final='' up=0 sum=0 this='' for i in range(maxlength)[::-1]: sum=0 for j in range(len(n)): sum=sum+int(sol[j][i]) thisdigit=str((sum+up)%10) up=(sum+up)/10 final=thisdigit+final #可能会进位 final=str(up)+final #最后处理这个字符串 去掉左侧0 if int(final)==0: final='0' else: k=0 for i in range(len(final)): if final[i]!='0': final=final[i:] break return final
0 0
- https://leetcode.com/problems/multiply-strings/
- https://leetcode.com/problems/candy/
- https://leetcode.com/problems/sqrtx/
- https://oj.leetcode.com/problems/majority-element/
- https://leetcode.com/problems/longest-common-prefix/
- https://leetcode.com/problems/pascals-triangle/
- https://leetcode.com/problems/powx-n/
- https://leetcode.com/problems/reverse-integer/
- https://leetcode.com/problems/plus-one/
- https://leetcode.com/problems/unique-paths/
- https://leetcode.com/problems/palindrome-number/
- https://leetcode.com/problems/permutation-sequence/
- https://leetcode.com/problems/climbing-stairs/
- https://leetcode.com/problems/divide-two-integers/
- https://leetcode.com/problems/add-binary/
- https://leetcode.com/problems/add-two-numbers/
- https://leetcode.com/problems/merge-sorted-array/
- https://leetcode.com/problems/first-missing-positive/
- 小米配置文件
- Django的是如何工作的
- call和apply的区别
- LightOJ 1356 && LightOJ 1336
- Android TabActivity使用
- https://leetcode.com/problems/multiply-strings/
- Step into Scala - 16 - 样本类与模式匹配
- 协方差与相关系数
- mysql sql mode详解
- 工业化社会的四次变革
- 用千分位格式化数据“123456789”
- linux shell “永久环境变量”、“临时环境变量”和"普通变量"之完全解读
- [leetcode] 47.Permutations II
- 第一篇文(写在最前面)