Add Binary

来源:互联网 发布:安邦和谐健康 知乎 编辑:程序博客网 时间:2024/06/03 06:02

c++

class Solution {public:    string addBinary(string a, string b) {        if (a.empty()) return b;        if (b.empty()) return a;        int i = a.size() - 1;        int j = b.size() - 1;        int update = 0;        string res;        while (i >= 0 && j >= 0) {            update += (a[i--] - '0') + (b[j--] - '0');            res.push_back(update % 2 + '0');            update /= 2;        }        while (i >= 0) {            update += (a[i--] - '0');            res.push_back(update % 2 + '0');            update /= 2;        }        while (j >= 0) {            update += (b[j--] - '0');            res.push_back(update % 2 + '0');            update /= 2;        }        if (update == 1)            res.push_back(update + '0');        reverse(res.begin(), res.end());        return res;    }};

python

class Solution(object):    def addBinary(self, a, b):        """        :type a: str        :type b: str        :rtype: str        """        if not a: return b        if not b: return a        a, b = list(a), list(b)        i, j = len(a)-1, len(b)-1        update = 0        res = []        while i>=0 and j>=0:            update += int(a[i])+int(b[j])            res.append(str(update%2))            update /= 2            i -= 1            j -= 1        while i>=0:            update += int(a[i])            res.append(str(update%2))            update /= 2            i -= 1        while j>=0:            update += int(b[j])            res.append(str(update%2))            update /= 2            j -= 1        if update ==1:            res.append(str(update))        return ''.join(res[::-1])
0 0
原创粉丝点击