Leetcode # 67. Add Binary

https://leetcode.com/problems/add-binary

Solution

Time Complexity: O(max(len(a), len(b))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)

class Solution:
  def addBinary(self, a: str, b: str) -> str:
    c = 0
    result = ""
    for i in range(max(len(a), len(b))):
      a_i = (ord(a[-1 - i]) - 48) if i < len(a) else 0
      b_i = (ord(b[-1 - i]) - 48) if i < len(b) else 0
      _sum = a_i + b_i + c
      c = 1 if _sum >= 2 else 0
      result = chr(_sum % 2 + 48) + result
    result = ("1" if c == 1 else "") + result
    return result

 

Last Updated on 2023/08/16 by A1go

目錄

目錄
Bitnami