Thursday, July 9, 2015

leetcode 67: add binary

Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".

 这个题目是实现bianry sum, 时间复杂度O(n), 空间复杂度O(1), 在原长字符串上面进行加法,
class Solution {
public:
    string addBinary(string a, string b) {
        //sanity check
        if (a.size() == 0) return b;
        if (b.size() == 0) return a;
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());
        if (a.size() < b.size()) {
            string tmp = a;
            a = b;
            b = tmp;
        }
        int cnt = 0;
        int i = 0;
        for (i = 0; i < b.size(); i++) {
            if ((a[i] - '0') + (b[i] - '0') + cnt >= 2) {
                a[i] = ((a[i] - '0') + (b[i] - '0') + cnt) % 2 + '0';
                cnt = 1;
            } else {
                a[i] = (a[i]-'0') + (b[i]-'0') + cnt + '0';
                cnt = 0;
            }
        }
        for (; i < a.size(); i++) {
            if (a[i] + cnt - '0' >= 2) {
                a[i] = ((a[i] - '0') + cnt) % 2 + '0';
                cnt = 1;
               
            }else {
                a[i] = a[i] + cnt;
                cnt = 0;
            }
        }
        if (cnt == 1) {
            a =  a + '1';
        }
        reverse(a.begin(), a.end());
        return a;
    }
};

写一个简洁版的:
当指针移出b的size,那么将b的值设为0, 否则直接用b的值,这样就可以统一a的指针超出b的size范围。
class Solution {
public:
    string addBinary(string a, string b) {
        //sanity check
        if (a.size() == 0) return b;
        if (b.size() == 0) return a;
        reverse(a.begin(), a.end());
        reverse(b.begin(), b.end());
        if (a.size() < b.size()) {
            string tmp = a;
            a = b;
            b = tmp;
        }
        int cnt = 0;
        int i = 0;
        for (i = 0; i < a.size(); i++) {
            int tt = 0;
            if (i <=  b.size()-1) tt = b[i]-'0';
            else tt = 0;
            if ((a[i] - '0') + tt + cnt >= 2) {
                a[i] = ((a[i] - '0') + tt + cnt) % 2 + '0';
                cnt = 1;
            } else {
                a[i] = (a[i]-'0') + tt + cnt + '0';
                cnt = 0;
            }
        }
        if (cnt == 1) {
            a =  a + '1';
        }
        reverse(a.begin(), a.end());
        return a;
    }
};

No comments:

Post a Comment