1、题目
67. Add Binary——easy
Given two binary strings, return their sum (also a binary string).
The input strings are both non-empty and contains only characters 1 or 0.
Example 1:
Input: a = "11", b = "1"
Output: "100"
Example 2:
Input: a = "1010", b = "1011"
Output: "10101"
2、我的解答
1 # -*- coding: utf-8 -*- 2 # @Time : 2020/2/9 11:18 3 # @Author : SmartCat0929 4 # @Email : 1027699719@qq.com 5 # @Link : https://github.com/SmartCat0929 6 # @Site : 7 # @File : 67. Add Binary.py 8 9 10 class Solution: 11 def addBinary(self, a: str, b: str) -> str: 12 a1 = "0b" + a 13 b1 = "0b" + b 14 sum1 = int(a1, 2) + int(b1, 2) #第一步 转换成十进制后的简单相加 15 sum2 = bin(sum1) #第二步 将相加后的和转换成二进制 16 a = [x for x in sum2] #第三步 bin方法转换后的二进制有0b前缀,用列表生成式将他转换成列表 17 b = a[2:] #第四步 采用切片,去除前两位前缀 18 sum3 = ‘‘.join(b) #第五步 采用join方法将列表内部元素合并 19 return sum3 20 print(Solution().addBinary("1010", "1011"))
原文:https://www.cnblogs.com/Smart-Cat/p/12286806.html