[LeetCode 415] Add Strings(Python)
来源:互联网 发布:《java从入门到精通》 编辑:程序博客网 时间:2024/06/06 00:30
题目描述
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
阅读全文
0 0
- [LeetCode 415] Add Strings(Python)
- Leetcode 415 Add Strings
- LeetCode[415] Add Strings
- LeetCode #415: Add Strings
- 【leetcode】415 Add Strings
- Leetcode Add Strings 415
- leetcode-415-Add Strings
- [Leetcode] #415 Add Strings
- leetcode[415]:Add Strings
- LeetCode 415 Add Strings
- Leetcode 415 Add Strings
- [leetcode: Python]415. Add Strings
- LeetCode.415(43) Add Strings&&Multiply Strings
- 【LeetCode】415 Add Strings (java实现)
- Sum—LeetCode-415 Add Strings
- Leetcode-415. Add Strings
- LeetCode 415. Add Strings
- [LeetCode]--415. Add Strings
- javascript – 为什么null是一个对象,null和undefined之间有什么区别?(最通俗的解释,推荐)
- java mail发送邮件
- 架构师的能力模型
- Python 安装
- Vue-cli创建vue项目以及配置文件梳理
- [LeetCode 415] Add Strings(Python)
- 独立看门狗
- IntelliJ Idea 常用快捷键列表
- [FreeBSD] 文件系统自检失败处理
- C# Async与Await的使用
- Java+opencv3.2.0之hough圆检测
- Python strip() lstrip() rstrip() 函数 去除空格
- js 写 select 对应年的 自然周-日期 动态下拉列
- js关闭浏览器时清除本地缓存