ADD Binary [Easy] (Python)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.