玩命加载中 . . .

67-二进制求和


LeetCode 67. Add Binary

Given two binary strings a and b, return their sum as a binary string.

Example 1:

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

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

method

  • 十进制加法,先两个加数求和,模以10作为当前位的结果,再除以10作进位
  • 二进制加法,先两个加数求和,模以2作为当前位的结果,再除以2作进位
string addBinary(string a, string b) {
    int carry = 0;
    string res = "";
    int i = a.size() - 1;
    int j = b.size() - 1;
    while (i >= 0 || j >= 0 || carry) {
        carry += i >= 0 ? a[i--] - '0' : 0;
        carry += j >= 0 ? b[j--] - '0' : 0;
        res = char(carry % 2 + '0') + res;
        carry = carry / 2;
    }
    return res;
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录