LeetCode : Add Binary

来源:互联网 发布:好的代理软件 编辑:程序博客网 时间:2024/06/08 16:02

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 res = "";        int curry = 0;        int i, j;        for (i = a.length() - 1, j = b.length() - 1; i >= 0 && j >= 0; --i, --j)        {            if (((a[i] - '0') + (b[j] - '0')+curry) >=2)            {                res += ((curry + (a[i] - '0') + (b[j] - '0'))%2 + '0');                curry = 1;            }            else            {                res += ((curry+'0' + ((a[i] - '0') + (b[j] - '0')) % 2) % 2 + '0');                curry = 0;            }        }        while (i >= 0)        {            if (((a[i] - '0')  + curry) >= 2)            {                res += ((curry + (a[i] - '0')) % 2 + '0');                curry = 1;            }            else            {                res += ((curry + (a[i] - '0')) % 2 + '0');                curry = 0;            }            --i;        }        while (j >= 0)        {            if (((b[j] - '0') + curry) >= 2)            {                res += ((curry + (b[j] - '0')) % 2 + '0');                curry = 1;            }            else            {                res += ((curry + (b[j] - '0')) % 2 + '0');                curry = 0;            }            --j;        }        if (curry == 1)            res += '1';        reverse(res.begin(), res.end());        return res;    }};
0 0
原创粉丝点击