1. 程式人生 > >(LeetCode每日一刷16)二進位制求和

(LeetCode每日一刷16)二進位制求和

題目描述:

給定兩個二進位制字串,返回他們的和(用二進位制表示)。

輸入為非空字串且只包含數字 1 和 0

 

示例:

示例 1:

輸入: a = "11", b = "1"
輸出: "100"

示例 2:

輸入: a = "1010", b = "1011"
輸出: "10101"

 

我提交的程式碼:

class Solution {
public:
    string addBinary(string a, string b) {
        string result;
        string new_result;
        int len = 0;
        int a_size = a.size();
        int b_size = b.size();
        if(a_size > b_size){
            len = a_size - b_size;
            for(int i = 0; i < len; ++i){
                b.insert(b.begin(),'0');
            }
        }
        else if(b_size > a_size){
            len = b_size - a_size;
            for(int i = 0; i < len; ++i){
                a.insert(a.begin(),'0');
            }
        }
        
        bool bPlus = 0;
        len = a.size();
        for (int i = len - 1; i >= 0; --i){
            int addResult = a[i] - '0' + b[i] - '0' + bPlus;
            if(addResult >= 2){
                if(addResult == 2)
                    result.push_back('0');
                else
                     result.push_back('1');
                bPlus = 1;
            }
            else{
                if(addResult == 0){
                    result.push_back('0');
                }
                else{
                    result.push_back('1');
                }         
                bPlus = 0;               
            }          
        }
        if(bPlus == 1){
            result.push_back('1');
        }
        
        for (int i = 0; i < result.size(); ++i){
            new_result.push_back(result[result.size() - i - 1]);
        }
        
        return new_result;                               
        
    }
};