Thursday, April 18, 2013

Day 18, 67 Add Binary

Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
-------------------
Solution #1, Straight forward
class Solution {
public:
    string addBinary(string a, string b) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int pre = 0, length = 0;
        string lon,sht;
        // find the longer string
        if (a.length() > b.length()) {
            length = a.length();
            lon = a;
            sht = b;
        }else {
            length = b.length();
            lon = b;
            sht = a;
        }
        for (int i=length-1;i>=0;i--) {
            if (sht.length() >= length - i) {
                if (sht[sht.length() - length + i] == '1' && lon[i] == '1') { // 1 + 1
                    if (pre == 0) {
                        lon[i] = '0';
                        pre = 1;
                    }
                }else if (sht[sht.length() - length + i] == '0' && lon[i] == '0') { // 0 + 0
                    if (pre == 1) {
                        lon[i] = '1';
                        pre = 0;
                    }
                }else if (pre == 1) { // '0'+'1'
                    lon[i] = '0';
                    pre = 1;
                }else {
                    lon[i] = '1';
                }
            }else { // short string ends, long string continues 
                if (pre == 1) {
                    if (lon[i] == '1') {
                        lon[i] = '0';
                    }else {
                        lon[i] = '1';
                        pre = 0;
                    }
                }
            }
        }
        if (pre == 1) { // one more digit
            lon = '1' + lon;
        }
        return lon;
    }
};
Update on Jul-10-2015
Solution #2, 加法时转化为integer
class Solution {
public:
    string addBinary(string a, string b) {
        int m = a.length(), n = b.length();
        int len = max(m,n);
        int carry = 0;
        string s = "";
        
        for (int i = 0; i < len; i++) {
            if (i < m) {
                carry += a[m - 1 - i] - '0';
            }
            if (i < n) {
                carry += b[n - 1 - i] - '0';
            }
            
            char sum = carry % 2 + '0';
            s = sum + s;
            carry = carry / 2;
        }
        
        if (carry) s = '1' + s;
        return s;
    }
};

No comments:

Post a Comment