LeetCode C++ 67. Add Binary【Math/String】簡單

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Constraints:

  • Each string consists only of '0' or '1' characters.
  • 1 <= a.length, b.length <= 10^4
  • Each string is either "0" or doesn’t contain any leading zero.

題意:對兩個二進制字符串進行加法運算。

思路:先翻轉 ab ,然後從頭開始相加即可。不過下面的代碼寫得太過繁瑣了。emmm,其實可以不必翻轉,也不必寫後面兩個循環。等有時間了,更新一下。先打卡再說。

代碼:

class Solution {
public:
    string addBinary(string a, string b) {
        string c;
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());
        int size = min(a.size(), b.size()), carry = 0;
        for (int i = 0; i < size; ++i) {
            int x = a[i] - '0', y = b[i] - '0', z = x + y + carry;
            c.push_back(z % 2 + '0');
            carry = z / 2;
        }
        for (int i = size; i < a.size(); ++i) {
            int k = a[i] - '0' + carry;
            c.push_back(k % 2 + '0');
            carry = k / 2;
        }
        for (int i = size; i < b.size(); ++i) {
            int k = b[i] - '0' + carry;
            c.push_back(k % 2 + '0');
            carry = k / 2;
        }
        if (carry) c.push_back(carry + '0');
        reverse(c.begin(), c.end());
        return c;
    }
};

效率:

執行用時:0 ms, 在所有 C++ 提交中擊敗了100.00% 的用戶
內存消耗:6.6 MB, 在所有 C++ 提交中擊敗了100.00% 的用戶
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章