[Leetcode]@python 67. Add Binary
2016-01-12 16:08
204 查看
题目链接:https://leetcode.com/problems/add-binary/
题目大意:给定两个二进制字符串,返回它们的和
解题思路:模拟二进制竖式加法
View Code
题目大意:给定两个二进制字符串,返回它们的和
解题思路:模拟二进制竖式加法
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ len_a = len(a) len_b = len(b) if len_a == 0: return b if len_b == 0: return a ans = "" carry = 0 while len_a > 0 and len_b: tmp = int(a[len_a - 1]) + int(b[len_b - 1]) + carry carry = tmp // 2 tmp %= 2 ans += str(tmp) len_a -= 1 len_b -= 1 if len_a == 0: while len_b > 0: tmp = int(b[len_b - 1]) + carry carry = tmp // 2 tmp %= 2 ans += str(tmp) len_b -= 1 if len_b == 0: while len_a > 0: tmp = int(a[len_a - 1]) + carry carry = tmp // 2 tmp %= 2 ans += str(tmp) len_a -= 1 if carry == 1: ans += str(carry) ans = ans[::-1] return ans
View Code
相关文章推荐
- Python简单读写Excel (xlwt, xlrd, xlutils)
- Python的更多内容
- python 查看插件命令 pip freeze 以及django3.4链接mysql
- python + opencv 中 kp(关键点) 的形式及提取坐标方法
- 【极客学院】-python学习笔记-4-单线程爬虫 (提交表单抓取信息,实战练习)
- [Leetcode]@python 66. Plus One
- 笨办法学Python学习笔记 练习16
- twistd 启动Python服务
- Python -- dict 类
- Python标准库
- python常用随机函数及带权重随机实例
- Python 2.5.7 高阶函数
- python笔记-列表和元组
- 《Web Scraping with Python》读书笔记
- python 2.5.6 函数式编程
- python笔记-字符串
- python数字图像处理(8):对比度与亮度调整
- Python的 startswith 和endswith
- python 2.5.5 迭代器
- Python学习手册 - 09