题目来源:
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 b11 if size2 == 0:12 return a13 carry,ans = 0,""14 while size1 > 0 and size2 > 0:15 tmp = int(a[size1 -1]) + int(b[size2 - 1]) + carry16 carry = tmp // 2;tmp %= 217 ans += str(tmp)18 size1 -= 1;size2 -= 119 if size1 == 0:20 while size2 > 0:21 tmp = int(b[size2 - 1]) + carry22 carry = tmp // 2;tmp %= 223 ans += str(tmp)24 size2 -= 125 if size2 == 0:26 while size1 > 0:27 tmp = int(a[size1 - 1]) + carry28 carry = tmp // 2;tmp %= 229 ans += str(tmp)30 size1 -= 131 if carry == 1:32 ans += str(carry)33 ans = ans[::-1]34 return ans
转载请注明出处:http://www.cnblogs.com/chruny/p/5028769.html