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);

}

你可能感兴趣的:(LeetCode)