LeetCode67. Add Binary(二進位制加法)

weixin_33913332發表於2019-01-16

題目

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

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

答案

  1. 從後往前加,一次迴圈後res代表進位加的數
string addBinary(string a, string b) {
    int m = a.length() - 1, n = b.length() - 1;
    int res = 0;
    string sum = "";
    while (m >= 0 || n >= 0 || res == 1) {
        res += m >= 0 ? a[m--] - '0' : 0;
        res += n >= 0 ? b[n--] - '0' : 0;
        sum = char(res % 2 + '0') + sum;
        res /= 2;
    }
    return sum;
}
  1. 日常python一行
def addBinary(self, a, b):
    return bin(int(a,2)+int(b,2))[2:]

相關文章