LeetCode 67. Add Binary/ 66. Plus One

本文提供了解决两个特定编程问题的方法:一是给定两个二进制字符串,返回它们相加后的二进制字符串;二是给定一个非负数的数字数组表示形式,对其进行加一操作。通过具体的代码实现展示了如何处理进位逻辑。

1. 题目描述

67.

Given two binary strings, return their sum (also a binary string).

For example,
a = “11”
b = “1”
Return “100”.

66.

Given a non-negative number represented as an array of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

2. 解题思路

总觉的, 这两道题目有一定的相似性, 可能是都需要借助一个临时变量保存进位信息吧

3. code

3.1 67

class Solution {
public:
    string addBinary(string a, string b) {
        int addition = 0;
        int len_a = a.size();
        int len_b = b.size();
        string res;
        for (int i = len_a - 1, j = len_b - 1; i >= 0 || j >= 0 || addition > 0; i--, j--){
            int sum = (i >= 0 ? a[i] - '0' : 0) + (j >= 0 ? b[j] - '0' : 0) + addition;
            res = to_string(sum % 2) + res;
            addition = sum / 2;
        }
        return res;
    }
};

3.2 66

class Solution {
public:
    vector<int> plusOne(vector<int>& digits) {
        vector<int> res;
        int addone = 1;
        for (int i = digits.size() - 1; i >= 0 || addone > 0; i--){
            int num = (i >= 0 ? digits[i] : 0) + addone;
            res.push_back(num % 10);
            addone = num / 10;
        }
        return vector<int>(res.rbegin(), res.rend());
    }
};

4. 大神解法

4.1 67

class Solution
{
public:
    string addBinary(string a, string b)
    {
        string s = "";

        int c = 0, i = a.size() - 1, j = b.size() - 1;
        while(i >= 0 || j >= 0 || c == 1)
        {
            c += i >= 0 ? a[i --] - '0' : 0;
            c += j >= 0 ? b[j --] - '0' : 0;
            s = char(c % 2 + '0') + s;
            c /= 2;
        }

        return s;
    }
};

4.2 66

避免了进位时候涉及对数组的移动操作 brilliant!!

void plusone(vector<int> &digits)
{
    int n = digits.size();
    for (int i = n - 1; i >= 0; --i)
    {
        if (digits[i] == 9)
        {
            digits[i] = 0;
        }
        else
        {
            digits[i]++;
            return;
        }
    }
        digits[0] =1;
        digits.push_back(0);

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值