leetcode -- Add Binary -- 简单要了解

来源:互联网 发布:mac怎么传照片给iphone 编辑:程序博客网 时间:2024/06/06 11:36

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

知道二进制加法原理即可,这里只需要知道进位是除数,余数是结果就行。最后不要忽略reg里面的值

class Solution(object):    def addBinary(self, a, b):        """        :type a: str        :type b: str        :rtype: str        """        if not a:            return b        elif not b:            return a        tmp_str = ''.join(['0'] * abs(len(a) - len(b)))        if tmp_str:            if len(a) > len(b):                b = tmp_str + b            else:                a = tmp_str + a        reg = 0        res = ''        for i in xrange(len(a) - 1, -1, -1):            tmp = int(a[i]) + int(b[i]) + reg            mod, inc = tmp % 2, tmp / 2            res = str(mod) + res            #print (reg,tmp, mod, inc, res)            reg = inc        if reg != 0:            res = '1' + res        return res

看这个博客。整理的解题思路

http://c4fun.cn/blog/2014/03/20/leetcode-solution-02/

0 0
原创粉丝点击