zoukankan      html  css  js  c++  java
  • 【leetcode】67. Add Binary

    题目如下:

    解题思路:首先将较短的输入前面补0,保证a和b长度一样,然后逐位相加再加上进位的值。如果和为3,当前位值为1,进位1;如果为2,当前位值为0,进位为1;否则不进位,当前位值即为和的值。

    代码如下:

    class Solution(object):
        def addBinary(self, a, b):
            """
            :type a: str
            :type b: str
            :rtype: str
            """
            diff = abs(len(a) - len(b))
            if len(a) < len(b):
                a = '0'*diff + a
            elif len(b) < len(a):
                b= '0'*diff + b
            carry = 0
            res = ''
            for i,j in zip(a[::-1],b[::-1]):
                v = int(i) + int(j) + carry
                if v == 3:
                    v = 1
                    carry = 1
                elif v == 2:
                    v = 0
                    carry = 1
                else:
                    carry = 0
                res = str(v) + res
            if carry > 0:
                res = str(carry) + res
            return res
            
  • 相关阅读:
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    LeetCode
    iOS开发系列--IOS程序开发概览
    iOS开发系列—Objective-C之Foundation框架
  • 原文地址:https://www.cnblogs.com/seyjs/p/9275618.html
Copyright © 2011-2022 走看看