LeetCode.67バイナリ加算(python解法)


目次
  • solution_1
  • 参考資料
  • タイトル
    2つのバイナリ文字列を指定し、それらの和(バイナリで表される)を返します.
    空白以外の文字列として入力し、数値1と0のみを入力します.
    例1:
      : a = "11", b = "1"
      : "100"
    

    例2:
      : a = "1010", b = "1011"
      : "10101"
    

    solution_1
    考え方:最下位から順番に和を求め、進位に注意すればいい.
    結果:実行時間:28 msランキング:69.48%勝利
    コードは次のとおりです.
    class Solution(object):
        def addBinary(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            total_num = ''
            i, j = 0, 0
            carry = 0  #   
            while i<len(a) or j<len(b):
                x, y = 0, 0
                if i<len(a):
                    x = int(a[len(a)-1-i])
                if j<len(b):
                    y = int(b[len(b)-1-j])
                if x + y + carry >= 2:  #    
                    this_num = x + y + carry - 2
                    carry = 1
                else:  #    
                    this_num = x+y+carry
                    carry = 0
                total_num = str(this_num) + total_num
                i += 1
                j += 1
            if carry == 1:  #    
                total_num = '1'+total_num
            return total_num
    

    参考資料
    バイナリ加算