[大数加法]Add Binary

一、题目

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

 

Subscribe to see which companies asked this question

 
二、解析
本科时学会的第一个算法...大数加的时候,将字符串反转后按位加,记录进位。注意将int变为str,这样看到的数字其实不是数字,而是字符串,从而实现大数显示。
 
三、代码
1.
class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        a = a[::-1]; b = b[::-1]
        lenA = len(a); lenB = len(b)
        
        if lenA > lenB:
            b += (lenA - lenB) * '0'
        else:
            a += (lenB - lenA) * '0'
            
        maxlen = max(lenA, lenB)
        rst = ""
        extra = 0
        temp = 0
        
        if maxlen == 0:
            return ""
        
        for i in range(maxlen):
            temp = int(a[i]) + int(b[i]) + extra
            if temp >= 2:
                temp = temp % 2
                extra = 1
            else:
                extra = 0
            rst += str(temp)
            
        if extra == 1:
            rst += '1'
        
        return rst[::-1]
            
                
        

 

2.一行方法:

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        return str(bin(int(a,2)+int(b,2)))[2:]
        
            
        
posted @ 2015-11-04 17:15  面包包包包包包  阅读(150)  评论(0编辑  收藏  举报