码迷,mamicode.com
首页 > 编程语言 > 详细

[leetcode] Add Binary @Python

时间:2014-09-16 10:31:00      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   for   div   

题目: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

标签:style   blog   http   color   io   os   ar   for   div   

原文地址:http://www.cnblogs.com/asrman/p/3974226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!