Topic links
https://leetcode.com/problems/add-binary/
Original title
Given binary strings, return their sum (also a binary string).
For example,
A = "11"
b = "1"
Return "100".
Topic translation
Given two binary strings, returns their and (also the binary string).
For example: a = "one", B = "1", return "100".
Method of ThinkingIdea one
With the Python conversion function, two addend are converted to 10, and then converted to binary return. Although it's pretty fast, it ignores the details of the possible large integers (because Python handles it for you).
Code
class Solution(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ return22))[2:]
Idea two
Starting with the lowest bits of the two strings, one-by-one is added to the binary, and the carry is saved, resulting in a string of both.
Code
class solution(object): def addbinary(self, A, b): "" : Type A:str:type b:str:rtype:str "" "res ="'I, j, plus = Len (a)-1, Len (b)-1,0 whilei>=0 orj>=0 orplus==1: Plus + = Int (A[i])ifi>=0 Else 0Plus + = Int (B[j])ifj>=0 Else 0res = str (plus%2) + res I, j, plus = i1, J-1, plus/2 returnRes
Three Ideas
With recursion, be aware that when two addend are 1 o'clock to carry.
Code
class solution(object): def addbinary(self, A, b): "" : Type A:str:type b:str:rtype:str "" " if notAor notB:returnAifAElseBifa[-1] ==' 1 ' andb[-1] ==' 1 ':returnSelf.addbinary (Self.addbinary (a[:-1], b[:-1]),' 1 ') +' 0 ' elifa[-1] ==' 0 ' andb[-1] ==' 0 ':returnSelf.addbinary (a[:-1], b[:-1]) +' 0 ' Else:returnSelf.addbinary (a[:-1], b[:-1]) +' 1 '
PS: Novice Brush Leetcode, new handwritten blog, write wrong or write not clear also please help point out, thank you!
Reprint Please specify: http://blog.csdn.net/coder_orz/article/details/51706532
ADD Binary [Easy] (Python)