LeetCode--067--二进制求和

问题描述:

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

输入为非空字符串且只包含数字 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

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