leetcode_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) {
        string longer;
        string shorter;
        string sum;
        stack<char> mys;
        int up = 0;
        if(a.size() > b.size()){
            longer = a;
            shorter = b;
        }else{
            longer = b;
            shorter = a;
        }
        int j = 0;
        for(int i = longer.size()-1; i >=0; i--){
            if(j < shorter.size()){
                if(longer[i] - '0' + shorter[shorter.size()-1-j] - '0' + up == 0){
                    up = 0;
                    mys.push('0');
                    j++;
                }
                else if(longer[i] - '0' + shorter[shorter.size()-1-j] - '0' + up == 1){
                    up = 0;
                    mys.push('1');
                    j++;
                }
                else if(longer[i] - '0' + shorter[shorter.size()-1-j] - '0' + up == 2){
                    up = 1;
                    mys.push('0');
                    j++;
                }
                else if(longer[i] - '0' + shorter[shorter.size()-1-j] - '0' + up == 3){
                    up = 1;
                    mys.push('1');
                    j++;
                }
            }
            else{
                if(longer[i] - '0' + up == 0){
                    up = 0;
                    mys.push('0');
                }
                else if(longer[i] - '0'  + up == 1){
                    up = 0;
                    mys.push('1');
                }
                else if(longer[i] - '0' + up == 2){
                    up = 1;
                    mys.push('0');
                }
            }
        }
        if(up == 1){
            mys.push('1');
        }
        while(!mys.empty()){
            sum += mys.top();
            mys.pop();
        }
        return sum;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章