67. Add Binary [easy] (Python)
2016-06-18 17:29
555 查看
题目链接
https://leetcode.com/problems/add-binary/题目原文
Given two binary strings, return their sum (also a binary string).For example,
a = “11”
b = “1”
Return “100”.
题目翻译
给定两个二进制字符串,返回它们的和(也是二进制字符串)。比如:a = “11”,b = “1”,返回 “100”。
思路方法
思路一
利用Python的进制转换函数,先将两个加数转成10进制,再把和转换成二进制返回即可。虽然速度还挺快的,但这么做忽略了可能的大整数相加的细节(因为Python帮你处理了)。代码
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ return bin(int(a, 2) + int(b, 2))[2:]
思路二
从两个字符串的最低位开始,一位一位的进行二进制相加,并保存进位,最终可以得到两者的和的字符串。代码
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ res = '' i, j, plus = len(a)-1, len(b)-1, 0 while i>=0 or j>=0 or plus==1: plus += int(a[i]) if i>= 0 else 0 plus += int(b[j]) if j>= 0 else 0 res = str(plus % 2) + res i, j, plus = i-1, j-1, plus/2 return res
思路三
用递归实现,要注意,当两个加数都是1时要进位。代码
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ if not a or not b: return a if a else b if a[-1] == '1' and b[-1] == '1': return self.addBinary(self.addBinary(a[:-1], b[:-1]), '1') + '0' elif a[-1] == '0' and b[-1] == '0': return self.addBinary(a[:-1], b[:-1]) + '0' else: return self.addBinary(a[:-1], b[:-1]) + '1'
PS: 新手刷LeetCode,新手写博客,写错了或者写的不清楚还请帮忙指出,谢谢!
转载请注明:/article/11857873.html
相关文章推荐
- 【contains-duplicate】leetCode python实现
- Python安装新的package
- Python学习笔记(While循环)
- 14. Longest Common Prefix [easy] (Python)
- threading in Python - 简单小例子
- 【leetCode】 Balanced Binary Tree python版实现
- python3 标准库 urllib.request
- 关于Python中函数默认参数的研究
- python笔记一_简单的基础
- python之流程控制语句
- 203. Remove Linked List Elements [easy] (Python)
- Python Collections Counter
- python 跨语言数据交互、json、pickle(序列化)、urllib、requests(爬虫模块)、XML。
- Python中找list中最大n个数的包heapq.nlargest
- 257. Binary Tree Paths [easy] (Python)
- 双色球 python
- 搞不懂 numpy.sum 请过来
- 记录
- python用openpyxl操作excel
- python用openpyxl操作excel