LeetCode - 解题笔记 - 67 - Add Binary

Solution 1

和前一个题类似,这里也是进行加法逻辑的实现。区别在于这里是二进制,验证的过程相对复杂一些。其他的没有区别,也是需要注意一下最后一次加法运算的结果。

但是看了一下别人的题解,好像我这么写虽然也是模拟加法,但是好像很拧巴……

  • 时间复杂度: O ( n ) O(n) O(n),其中 n n n为输入较大字符串的长度,线性遍历
  • 空间复杂度: O ( 1 ) O(1) O(1),只维护常数个状态变量,但是如果创建新字符串占用对应的空间
class Solution {
public:
    string addBinary(string a, string b) {
        int carry = 0;
        string testa = a.size() > b.size() ? a : b;
        string testb = a.size() <= b.size() ? a : b;
        for (int i = testa.size() - 1; i >= 0; --i) {
            int temp = 0;
            if ((testa.size() - i) > testb.size()) {
                temp = testa[i] - 48 + carry;

            }
            else {
                temp = testa[i] - 48 + testb[testb.size() - (testa.size() - i)] - 48 + carry;
            }
            if (temp > 1) {
                testa[i] = temp - 2 + 48;
                carry = 1;
            }
            else {
                testa[i] = temp + 48;
                carry = 0;
            }
        }
        string ans = testa;
        if (carry == 1) {
            ans = "1" + testa;
        }
        return ans;
    }
};

Solution 2

Solution 1的Python实现

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        carry = 0
        testa, testb = (list(a), list(b)) if len(a) > len(b) else (list(b), list(a))
        
        for i in range(len(testa) - 1, -1, -1):
            if len(testa) - i > len(testb):
                temp = int(testa[i]) + carry
            else:
                temp = int(testa[i]) + int(testb[len(testb) - (len(testa) - i)]) + carry
                
            if temp > 1:
                testa[i] = str(temp - 2)
                carry = 1
            else:
                testa[i] = str(temp)
                carry = 0
                
        ans = "".join(testa)
        if carry == 1: ans = "1" + "".join(testa)
            
        return ans
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值