[LeetCode 415] Add Strings(Python)
2017-08-25 16:14
363 查看
题目描述
Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.Note:
1.The length of both num1 and num2 is < 5100.
2.Both num1 and num2 contains only digits 0-9.
3.Both num1 and num2 does not contain any leading zero.
4.You must not use any built-in BigInteger library or convert the inputs to integer directly.
思路
按加法法则计算。用一个整数变量保存当前进位值,用以相加。代码
class Solution(object): def addStrings(self, num1, num2): """ :type num1: str :type num2: str :rtype: str """ res='' i = len(num1) -1 j = len(num2) - 1 # 进位值 carry = 0 while i >= 0 and j >= 0: sum = int(num1[i]) + int(num2[j]) + carry if sum < 10: carry = 0 res = str(sum) + res else: carry = 1 res = str(sum%10) + res i -= 1 j -= 1 while i != -1: sum = int(num1[i]) + carry if sum < 10: carry = 0 res = str(sum) + res else: carry = 1 res = str(sum % 10) + res i -= 1 while j != -1: sum = int(num2[j]) + carry if sum < 10: carry = 0 res = str(sum) + res else: carry = 1 res = str(sum % 10) + res j -= 1 if carry != 0: res = str(carry) + res return res
相关文章推荐
- Sum—LeetCode-415 Add Strings
- LeetCode[415] Add Strings
- leetcode-415-Add Strings
- 【LeetCode】415 Add Strings (java实现)
- LeetCode 415 Add Strings
- leetcode[415]:Add Strings
- 【LeetCode】415 Add Strings (java实现)
- leetcode_415 Add Strings
- Leetcode 415 Add Strings
- 【leetcode】415 Add Strings
- leetcode 日经贴,python code -Remove Duplicates from Sorted Array
- LeetCode 61 — Rotate List(C++ Java Python)
- leetcode hIndex implemented with python
- [LeetCode]Combination Sum@python
- leetcode—242. Valid Anagram 判断由颠倒字母顺序而构成的词,python字典的应用
- [Leetcode,python] Majority Element 众数
- leetcode:Pascal's Triangle【Python版】
- leetcode Combination Sum II python
- Leetcode 21 Python
- [leetcode] Search in Rotated Sorted Array @ Python [Figure][自配插图说明]