LeetCode-67. Add Binary

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"

题解:

class Solution {
public:
    string add(string a, string b, int n) {
        string s;
        int plus = 0;
        for (int i = n - 1; i >= 0; i--) {
            int num = plus + a[i] + b[i] - 96;
            if (num < 2) {
                s.insert(s.begin(), num + 48);
                plus = 0;
            }
            else {
                s.insert(s.begin(), num + 46);
                plus = 1; 
            }
        }
        if (plus == 1) {
            s.insert(s.begin(), '1');
        }
        return s;
    }
    string addBinary(string a, string b) {
        int n = a.length(), m = b.length();
        if (n < m) {
            for (int i = 0; i < m - n; i++) {
                a.insert(a.begin(), '0');
            }
        }
        else if (n > m) {
            for (int i = 0; i < n - m; i++) {
                b.insert(b.begin(), '0');
            }
        }
        return add(a, b, max(n, m));
    }
};

猜你喜欢

转载自blog.csdn.net/reigns_/article/details/89812608