Add Binary

LeetCode #67


Description:

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

Example:

For example,
a = "100"
b = "110010"
Return "100".

Idea:

先inverse俩string, 再加,再反结果。注意要不要增加节点。

Code:

class Solution {
public:
    string addBinary(string a, string b) {
        if(a.size()<b.size()){
            swap(a, b);
        }

        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());
        string result(a);

        int nb=b.size();
        int na=a.size();
        int carry=0;
        int num_a, num_b, sum_val;

        int i=0;
        while(i<nb){ // 先管短的
            num_a = a[i] - '0';
            num_b = b[i] - '0';
            sum_val = num_a + num_b + carry;
            result[i] = sum_val%2==0? '0' : '1';
            carry = sum_val/2;
            ++i;
        }
        while(carry!=0 && i<na){ // 再处理剩下的
            num_a = a[i] - '0';
            sum_val = num_a + carry;
            result[i] = sum_val%2==0? '0' : '1';
            carry = sum_val/2;
            ++i;
        }
        if(carry==1){ // 进一位
            result += '1';
        }

        reverse(result.begin(), result.end());
        return result;
    }
};

results matching ""

    No results matching ""