首页 > 代码库 > [leetcode] Add Binary @Python
[leetcode] Add Binary @Python
题目:https://oj.leetcode.com/problems/add-binary/
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
思路1: 直接利用内置函数 int, str. 注意bin(3) 输出为:‘0b11‘, 所以需要通过[2:]来删除前两个字符 (原创)
class Solution: # @param a, a string # @param b, a string # @return a string def addBinary(self, a, b): return bin( int( str( int(a,2) + int(b,2) ) ))[2:]
思路2: 假设混沌初开,我们只好连车轮也要自己造 :) (下面参考的是: http://chaoren.is-programmer.com/posts/42675.html)
class Solution: # @param a, a string # @param b, a string # @return a string def addBinary(self, a, b): length_a = len(a) length_b = len(b) if length_a > length_b: b = ‘0‘ * (length_a - length_b) + b length = length_a else: a = ‘0‘ * (length_b - length_a) + a length = length_b a = a[::-1] b = b[::-1] Sum = ‘‘ carry = 0 for i in xrange(length): tmp = ord(a[i]) - 48 + ord(b[i]) - 48 + carry Sum += str(tmp % 2) carry = tmp / 2 if carry == 1: Sum += ‘1‘ return Sum[::-1]
[leetcode] Add Binary @Python
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。