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%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章