首页 > 其他 > 详细

LeetCode--067--二进制求和

时间:2018-07-24 19:46:49      阅读:141      评论:0      收藏:0      [点我收藏+]

问题描述:

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0

示例 1:

输入: a = "11", b = "1"
输出: "100"

示例 2:

输入: a = "1010", b = "1011"
输出: "10101"

方法1:

 1 class Solution(object):
 2     def deci(self,nums):
 3         ans = 0
 4         nums = nums[::-1]
 5         for i in range(len(nums)):
 6             if nums[i] == 1:
 7                 ans += pow(2,i)
 8         return ans
 9     def addBinary(self, a, b):
10         """
11         :type a: str
12         :type b: str
13         :rtype: str
14         """
15         res = self.deci(a) + self.deci(b)
16         return bin(res)[2:]

方法2:

1 class Solution(object):
2     def addBinary(self, a, b):
3         """
4         :type a: str
5         :type b: str
6         :rtype: str
7         """
8         num = int(a,2) + int(b,2)
9         return bin(num)[2:]

2018-07-24 19:38:24

 

LeetCode--067--二进制求和

原文:https://www.cnblogs.com/NPC-assange/p/9362126.html

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