67. Add Binary

Posted 向日葵的祈愿

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了67. Add Binary相关的知识,希望对你有一定的参考价值。

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

For example,
a = "11"
b = "1"
Return "100

*/

class Solution {
public:
    string addBinary(string a, string b) {
        if (a == "" && b == "") return "";
        
        string result = "";
        int c = 0, i = a.length()-1, j = b.length()-1;
        while (i >= 0 || j >= 0) {
            
            c += i < a.length() ? (a[i] - 0) : 0;
            c += j < b.length() ? (b[j] - 0) : 0;
            
            result = char(c%2 + 0) + result;
            c /= 2;
            --i, --j;
        }
        
        return c ? char(c+0) + result : result;
    }
};

 

以上是关于67. Add Binary的主要内容,如果未能解决你的问题,请参考以下文章

leetcode67. Add Binary

67. Add Binary

LeetCode----67. Add Binary(java)

67. Add Binary

67. Add Binary

leetcode67. Add Binary