A 4ms C++ Solution, Relative long but easy to understand


  • 0
    Y
    class Solution {
    public:
        string addBinary(string a, string b) {
            int lenA = a.length();
            int lenB = b.length();
            int mark = 0;
            string ans = "";
            int i = lenA - 1, j = lenB - 1;
            while((i >= 0)&&(j >= 0)) {
                    if((a[i] - '0' + b[j] - '0' + mark) == 0) {
                        ans = '0' + ans;
                        mark = 0;
                    } else if((a[i] - '0' + b[j] - '0' + mark) == 1) {
                        ans = '1' + ans;
                        mark = 0;
                    } else if((a[i] - '0' + b[j] - '0' + mark) == 2) {
                        ans = '0' + ans;
                        mark = 1;
                    } else if((a[i] - '0' + b[j] - '0' + mark) == 3) {
                        ans = '1' + ans;
                        mark = 1;
                    }
                    i--;
                    j--;
            }
            if((i < 0)&&(j >= 0)) {
                for(int m = j; m >= 0; m--) {
                    if((b[m] - '0' + mark) == 0) {
                        ans = '0' + ans;
                        mark = 0;
                    } else if((b[m] - '0' + mark) == 1) {
                        ans = '1' + ans;
                        mark = 0;
                    } else if((b[m] - '0' + mark) == 2) {
                        ans = '0' + ans;
                        mark = 1;
                    }
                }
            } else if((j < 0)&&(i >= 0)) {
                for(int m = i; m >= 0; m--) {
                    if((a[m] - '0' + mark) == 0) {
                        ans = '0' + ans;
                        mark = 0;
                    } else if((a[m] - '0' + mark) == 1) {
                        ans = '1' + ans;
                        mark = 0;
                    } else if((a[m] - '0' + mark) == 2) {
                        ans = '0' + ans;
                        mark = 1;
                    }
                }
            }
            if(mark == 1) ans = '1' + ans;
            return ans;
        }
    };

Log in to reply
 

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