[LeetCode]题解(python):067-Add Binary

题目来源:

  https://leetcode.com/problems/add-binary/


 

题意分析:

  这题是要将二进制相加,比如“11”,“1”,那么就返回“100”。


 

题目思路:

  模拟加法的过程,直接模拟,大于等于2就进位。


 

代码(Python):

  

 1 class Solution(object):
 2     def addBinary(self, a, b):
 3         """
 4         :type a: str
 5         :type b: str
 6         :rtype: str
 7         """
 8         size1 = len(a);size2 = len(b)
 9         if size1 == 0:
10             return b
11         if size2 == 0:
12             return a
13         carry,ans = 0,""
14         while size1 > 0 and size2 > 0:
15             tmp = int(a[size1 -1]) + int(b[size2 - 1]) + carry
16             carry = tmp // 2;tmp %= 2
17             ans += str(tmp)
18             size1 -= 1;size2 -= 1
19         if size1 == 0:
20             while size2 > 0:
21                 tmp = int(b[size2 - 1]) + carry
22                 carry = tmp // 2;tmp %= 2
23                 ans += str(tmp)
24                 size2 -= 1
25         if size2 == 0:
26             while size1 > 0:
27                 tmp = int(a[size1 - 1]) + carry
28                 carry = tmp // 2;tmp %= 2
29                 ans += str(tmp)
30                 size1 -= 1
31         if carry == 1:
32             ans += str(carry)
33         ans = ans[::-1]
34         return ans
View Code

 


 

转载请注明出处:http://www.cnblogs.com/chruny/p/5028769.html

posted @ 2015-12-08 13:02  Ry_Chen  阅读(478)  评论(0编辑  收藏  举报