67. Add Binary

67. Add Binary

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

For example,
a = "11"
b = "1"
Return "100".
Analysis:
相当于自己写一个加法运算,主要是处理好进位与当前位之间的关系。还有注意空字符串。
本题跟66. Plus One 比较类似。
Source Code(C++):

#include <iostream>
#include <string>
using namespace std;

class Solution {
public:
    string addBinary(string a, string b) {
        char digit_overflow='0';
        char current_bit='0';
        int a_index=a.size()-1, b_index=b.size()-1;
        string sum;
        while(a_index>=0 && b_index>=0){
            current_bit=(a.at(a_index)-'0'+b.at(b_index)-'0'+digit_overflow-'0')%2 + '0';
            sum.insert(0, 1, current_bit);
            digit_overflow = (a.at(a_index)-'0'+b.at(b_index)-'0'+digit_overflow-'0')/2 + '0';          
            a_index--;
            b_index--;
        }
        while(a_index>=0){
            current_bit=(a.at(a_index)-'0'+digit_overflow-'0')%2 + '0';
            sum.insert(0, 1, current_bit);
            digit_overflow = (a.at(a_index)-'0'+digit_overflow-'0')/2 + '0';        
            a_index--;
        }
        while(b_index>=0){
            current_bit=(b.at(b_index)-'0'+digit_overflow-'0')%2 + '0';
            sum.insert(0, 1, current_bit);
            digit_overflow = (b.at(b_index)-'0'+digit_overflow-'0')/2 + '0';        
            b_index--;
        }
        if (digit_overflow > '0') {
            sum.insert(0, 1, digit_overflow);
        }
        return sum;
    }
};


int main() {
    Solution sol;
    cout << sol.addBinary("", "");
    cout << sol.addBinary("101", "1");
    cout << sol.addBinary("10", "11");
    return 0;
}

你可能感兴趣的:(67. Add Binary)