惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
Visual Studio Blog
A
About on SuperTechFans
J
Java Code Geeks
G
Google Developers Blog
L
LangChain Blog
小众软件
小众软件
宝玉的分享
宝玉的分享
云风的 BLOG
云风的 BLOG
P
Proofpoint News Feed
博客园 - 【当耐特】
IT之家
IT之家
F
Fortinet All Blogs
aimingoo的专栏
aimingoo的专栏
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
阮一峰的网络日志
阮一峰的网络日志
V
V2EX
博客园 - Franky
博客园_首页
雷峰网
雷峰网
Microsoft Security Blog
Microsoft Security Blog
Vercel News
Vercel News
B
Blog
月光博客
月光博客
酷 壳 – CoolShell
酷 壳 – CoolShell

博客园 - Dabay

[Leetcode][Python]56: Merge Intervals [Leetcode][Python]55: Jump Game [Leetcode][Python]54: Spiral Matrix [Leetcode][Python]53: Maximum Subarray [Leetcode][Python]52: N-Queens II [Leetcode][Python]51: N-Queens [Leetcode][Python]50: Pow(x, n) [Leetcode][Python]49: Anagrams [Leetcode][Python]48: Rotate Image [Leetcode][Python]47: Permutations II [Leetcode][Python]46: Permutations [Leetcode][Python]45: Jump Game II [Leetcode][Python]44:Wildcard Matching [Leetcode][Python]42: Trapping Rain Water [Leetcode][Python]41: First Missing Positive [Leetcode][Python]40: Combination Sum II [Leetcode][Python]39: Combination Sum [Leetcode][Python]19: Remove Nth Node From End of List [Leetcode][Python]37: Sudoku Solver
[Leetcode][Python]43: Multiply Strings
Dabay · 2015-03-23 · via 博客园 - Dabay
# -*- coding: utf8 -*-
'''
__author__ = 'dabay.wang@gmail.com'

43: Multiply Strings
https://leetcode.com/problems/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.

=== Comments by Dabay===
用小学学的乘法公式。
'''

class Solution:
# @param num1, a string
# @param num2, a string
# @return a string
def multiply(self, num1, num2):
if num1 == "0" or num2 == "0":
return "0"
# if len(num1) < len(num2):
# num1, num2 = num2, num1
res = ""
for j in reversed(xrange(len(num2))):
tmp = ""
carry = 0
for i in reversed(xrange(len(num1))):
x = int(num1[i]) * int(num2[j]) + carry
carry = x / 10
x = x % 10
tmp = str(x) + tmp
if carry != 0:
tmp = str(carry) + tmp
res = self.num_add(res, tmp + "0" * (len(num2)-1-j))
return res

def num_add(self, num1, num2):
if len(num1) > len(num2):
num2 = num2.zfill(len(num1))
else:
num1 = num1.zfill(len(num2))
res = ""
carry = 0
for i in reversed(xrange(len(num1))):
x = int(num1[i]) + int(num2[i]) + carry
if x >= 10:
x -= 10
carry = 1
else:
carry = 0
res = str(x) + res
if carry == 1:
res = "1" + res
return res

def main():
sol = Solution()
num1 = "999"
num2 = "999"
print sol.num_add(num1, num2)
print sol.multiply(num1, num2)

if __name__ == "__main__":
import time
start = time.clock()
main()
print "%s sec" % (time.clock() - start)