C++ simple


  • 0
    Y

    class Solution {
    public:
    string addBinary(string a, string b) {
    if (a == "") return b;
    if (b == "") return a;
    int sizeA = a.size();
    int sizeB = b.size();
    int temp;
    string answer = "";
    int carry=0;
    while (sizeA < sizeB) {
    a = "0" + a;
    sizeA++;
    }
    while (sizeA > sizeB) {
    b = "0" + b;
    sizeB++;
    }
    while (sizeA) {
    sizeA--, sizeB--;
    temp = int(a[sizeA]) + int(b[sizeB]) + carry - 96;
    carry = temp / 2;
    temp = temp % 2;
    answer = to_string(temp)+answer;
    }
    if (carry)
    answer = "1" + answer;
    return answer;
    }
    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.