iT邦幫忙

0

leetcode with python:67. Add Binary

題目:

Given two binary strings a and b, return their sum as a binary string.

給定兩個字串型態的二進位數,同樣以字串二進位型態返回相加結果

又是一題有偏方解的題目

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        a=int(a,2)
        b=int(b,2)
        ans=a+b
        ans=bin(ans)
        return ans[2::] #去掉前面的'0b'

將兩數用內建function轉十進位後相加再轉二進位
最後執行時間27ms(faster than 98.88%)

當然我們還是要回歸正常解,用類似之前進位的概念去做

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        temp=0
        i=0
        ans=""
        
        a=a[::-1] #先reverse便利操作
        b=b[::-1]
        
        while i<max(len(a),len(b)):
        
            if i>len(a)-1: #超出字串範圍值為0
                x=0
            else:
                x=int(a[i])
            if i>len(b)-1:
                y=0
            else:
                y=int(b[i])
                
            ans=str((x+y+temp)%2)+ans
            temp=(x+y+temp)//2
            i=i+1
            
        if temp!=0:
            ans=str(temp)+ans
        return ans

同一位數兩相相加,不過 > 2就要進位
特別注意結果要以字串形式加入要回傳的字串中
且留意是否有數突破最高位
最後執行時間35ms(faster than 90.31%)

那我們下題見


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言