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

Example

a = 11

b = 1

Return 100

 

LeetCode上的原题,请参见我之前的博客Add Binary

 

class Solution {
public:
    /**
     * @param a a number
     * @param b a number
     * @return the result
     */
    string addBinary(string& a, string& b) {
        string res = "";
        int m = a.size() - 1, n = b.size() - 1, carry = 0;
        while (m >= 0 || n >= 0) {
            int p = m >= 0 ? a[m--] - '0' : 0;
            int q = n >= 0 ? b[n--] - '0' : 0;
            int sum = p + q + carry;
            res = to_string(sum % 2) + res;
            carry = sum / 2;
        }
        return carry == 1 ? "1" + res : res;
    }
};

 

相关文章:

  • 2021-03-31
  • 2022-12-23
  • 2022-01-24
  • 2021-08-16
  • 2022-03-07
  • 2022-01-16
  • 2022-03-04
猜你喜欢
  • 2021-09-12
  • 2022-12-23
  • 2021-07-06
  • 2022-01-18
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案