Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

67. Add Binary #85

Open
tech-cow opened this issue Feb 10, 2020 · 2 comments
Open

67. Add Binary #85

tech-cow opened this issue Feb 10, 2020 · 2 comments
Projects

Comments

@tech-cow
Copy link
Owner

tech-cow commented Feb 10, 2020

No description provided.

@tech-cow tech-cow created this issue from a note in Facebook (Failure due to bugs (Bugs)) Feb 10, 2020
@tech-cow tech-cow moved this from Failure due to bugs (Bugs) to Weekend Oversee in Facebook Feb 10, 2020
@tech-cow
Copy link
Owner Author

First Try:

class Solution(object):
    def addBinary(self, a, b):
        a, b = a[::-1], b[::-1]
        m, n = len(a), len(b)
        diff = max(m, n) - min(m, n)
        
        for i in range(diff):
            if m < n : 
                a += "0"
            else:
                b += "0"
        
        carry = 0
        res = ""
        for i in range(max(m, n)):
            curSum = int(a[i]) + int(b[i]) + carry
            carry = 0
            if curSum == 3:
                carry += 1
                res += "1"
            elif curSum >= 2:
                carry += 1
                res += "0"
            else:
                carry = 0
                res += str(curSum)
        if carry:
            res += str(carry) 
        return res[::-1]

@tech-cow
Copy link
Owner Author

2x Try (1 Day Apart)

class Solution(object):
    def addBinary(self, a, b):
        i = len(a) - 1
        j = len(b) - 1
        
        carry = 0
        res = ""
      
        while i >= 0 or j >= 0 or carry:
            if i >= 0:
                carry += int(a[i])
                i -= 1
            if j >= 0:
                carry += int(b[j])
                j -= 1
            res = str(carry % 2) + res
            carry //= 2
        return res

@tech-cow tech-cow moved this from Weekend Oversee to 二刷 | 三刷 in Facebook Mar 19, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
Facebook
  
二刷 | 三刷
Development

No branches or pull requests

1 participant