LeetCode | 67. binary sum

Give you two binary string, and return them (in binary).

And a non-empty input string contains only numbers 0 and 1.

Example 1:

输入: a = "11", b = "1"
输出: "100"

Example 2:

输入: a = "1010", b = "1011"
输出: "10101"

prompt:

  • Each string only by the characters '0' or '1' composition.
  • 1 <= a.length, b.length <= 10^4
  • If the string is not "0", do not contain leading zeros.
/*
思路:对齐、相加、进位
*/
class Solution {
public:
    string addBinary(string a, string b) {
        int aLength = a.length();
        int bLength = b.length();
        int maxLength = max(aLength,bLength);
        string s(maxLength,'0');//最大length长度的‘0’组成
        //首先对齐
        if(aLength < bLength) a = string(bLength - aLength , '0') + a;
        else b = string(aLength - bLength , '0') + b;
        //然后从最低下标为1的相加、进位
        for(int i = maxLength - 1;i > 0; i--){
            s[i] +=a[i] - '0' + b[i] - '0';
            if(s[i] >= '2'){//进位
                s[i-1] += 1;
                s[i]   -= 2;
            }
        }
        //最高位相加
        s[0] +=a[0] - '0' + b[0] - '0';
        if(s[0] >= '2'){
            s[0] -= 2;
            s = '1' +s;
        }
        return s;
    }
};

Guess you like

Origin www.cnblogs.com/RioTian/p/12658921.html