Leetcode 067 二进制求和 Python C++

本人一直在努力地积累Leetcode上用Python, C++实现的题,并且会尽力讲清每道题的原理,绝不像其他某些博客简略地带过。
如果觉得讲的清楚,欢迎关注。

题目:

给定两个二进制字符串,返回他们的和(用二进制表示)。

输入为非空字符串且只包含数字 1 和 0

示例 1:

输入: a = "11", b = "1"
输出: "100"

示例 2:

输入: a = "1010", b = "1011"
输出: "10101"

算法过程:如果想锻炼自己不用Python 的包,主要有2种思路:

1.把a和b转成十进制后再相加再转成二进制

2.直接模拟2进制加法

这里直接贴出上述2种方法的代码:

1.

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        num1=num2=0
        z=0
        #转10进制
        while(1):
            if len(a) == 0:
                break
            num1=num1+pow(2,z)*int(a[-1])
            a=a[:-1]
            z+=1
        z = 0
        #转10进制
        while (1):
            if len(b) == 0:
                break
            num2 = num2 + pow(2, z) * int(b[-1])
            b = b[:-1]
            z += 1
        #加十进制
        sum = num1+num2
        #转2进制,当然也可以自己写
        sum = str(bin(sum)[2:])
        return sum

2.(完全没有用其他的包,只不过写的比较繁琐,因为写这道题的时候还很菜。。。)

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        i = 0
        res = ""
        step = 0
        #确定谁比较大(谁长度比较长)
        large = max(a, b ,key=len)
        small = min(a, b, key=len)
        #如果2者相同,随机分配
        if large == small:
            large = a
            small = b
        #从末尾开始模拟
        i = len(large) - 1
        j = len(small) - 1
        
        while i >= 0  and j >= 0:
            #计算
            ans = int(large[i]) + int(small[j]) + step #step用来记录有没有进位
            if ans > 1:
                res = str(ans-2) + res
                step = 1
            else:
                step = 0
                res = str(ans) + res
            i -= 1
            j -= 1
        #可能短的走完了长的还没走完
        while i >= 0:
            #如果step为0了,则简单了,直接把剩余部分搬过来
            if step == 0:
                res = large[:i+1] + res
                break
            #若step不为0,则继续模拟
            else:
                ans = int(large[i]) + step
                if ans > 1:
                    res = str(ans-2) + res
                    step = 1
                    i -= 1
                else:
                    res = large[:i] + str(ans) + res
                    step = 0
                    break
        #如果step还为1,证明这个进位一直传递到最高位了
        if step == 1:
            res = "1" + res
        return res

当然想简单,只需一行代码:

class Solution:
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """

        return bin(int(a,2)+int(b,2))[2:]

bin是用来把十进制转2进制的,取切片是因为前2位是表示二进制的一些字符。

int(a,2)的2的意思是告诉这个int函数,你要int的东西是个二进制而不是十进制。

C++

总体思路与方法2python类似,只不过这里用了一些技巧来简化代码,并且采用的是顺序加和,所以需要再结尾处反转结果。

class Solution {
public:
    string addBinary(string a, string b) {
        string ret;
        int la = a.length();
        int lb = b.length();
        int lmax = max(la, lb);
        int add = '0';
        for (int i = 0; i < lmax; i++) {
            //超出的部分就用'0'来代替
            char ca = la > i ? a[la-i-1] : '0';
            char cb = lb > i ? b[lb-i-1] : '0';
            char s = (ca == cb ? '0' : '1');
            char sj = (s == add ? '0' : '1');
            if (ca == '1' && cb == '1'
                    || s == '1' && add == '1') {
                add = '1';        
            } else {
                add = '0';
            }
            ret += sj;
        }
        if (add == '1') {
            ret += add;
        }
        reverse(ret.begin(), ret.end());
        return ret;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_41958153/article/details/81383838
今日推荐