首页 > 其他 > 详细

LeetCode练题——67. Add Binary

时间:2020-02-09 13:50:21      阅读:72      评论:0      收藏:0      [点我收藏+]

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

 

LeetCode练题——67. Add Binary

原文:https://www.cnblogs.com/Smart-Cat/p/12286806.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!