Title: https://oj.leetcode.com/problems/add-binary/
Given binary strings, return their sum (also a binary string).
For example,
A = "11"
b = "1"
Return "100".
Idea 1: Directly using the built-in function int, str. Note that the bin (3) output is: ' 0b11 ', so you need to delete the first two characters by [2:] (original)
class Solution: # @param A, a string # @param b, a string # @return A string def addbinary (self, A, b): return bin (int (str (a,2) + int (b,2))) [2:]
Train of thought 2: Suppose the chaos first opened, we had to even the wheel to build their own:) (See below for: http://chaoren.is-programmer.com/posts/42675.html)
classSolution:#@param A, a string #@param b, a string #@return A string defaddbinary (self, A, b): Length_a=Len (a) Length_b=Len (b)ifLength_a >length_b:b='0'* (Length_a-length_b) +B length=length_aElse: A='0'* (LENGTH_B-LENGTH_A) +a length=Length_b a= A[::-1] B= B[::-1] Sum="'Carry=0 forIinchxrange (length): tmp= Ord (A[i])-+ ord (B[i])-48 +Carry Sum+ = STR (tmp% 2) Carry= TMP/2ifcarry = = 1: Sum+='1' returnSUM[::-1]
[Leetcode] ADD Binary @Python