一、题目
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
二进制加法
二、解题思路
第一种:先将二进制转换成十进制,做十进制加法,然后再转回二进制,代码只有一行,简单粗暴,有点作弊的感觉;
第二种:做二进制加法,设置进位项,这里可以先做加法然后再反转字符串即可。
三、代码
#coding:utf-8 def addBinary1(a, b): """ :type a: str :type b: str :rtype: str """ print(bin(int(a, 2) + int(b, 2))[2:]) return bin(int(a, 2) + int(b, 2))[2:] def addBinary2(a,b): size_a = len(a) size_b = len(b) carry,ana = 0,"" if size_a == 0: return b if size_b == 0: return a while size_a > 0 and size_b > 0: tmp = int(a[size_a-1])+int(b[size_b-1])+carry carry = tmp // 2 tmp %=2 ana += str(tmp) size_a -= 1 size_b -= 1 if size_a == 0: while size_b > 0: tmp = int(b[size_b-1])+carry carry = tmp // 2 tmp %= 2 ana += str(tmp) size_b -= 1 if size_b == 0: while size_a > 0: tmp = int(a[size_a-1])+carry carry = tmp // 2 tmp %= 2 ana += str(tmp) size_a -= 1 if carry == 1: ana += str(carry) ana = ana[::-1] print(ana) return ana if __name__ == '__main__': a = "1" b = "111" addBinary2(a,b)
参考博客:https://www.cnblogs.com/asrman/p/3974226.html?utm_source=tuicool&utm_medium=referral