LeetCode: Add Binary

来源:互联网 发布:嵌入式linux实用教程 编辑:程序博客网 时间:2024/04/29 05:17

思路:模拟加法运算即可,注意最后进位的考虑,如果为1,还要增加一位来存储。

class Solution {public:    string addBinary(string a, string b) {        int len1 = a.size(), len2 = b.size();        vector<int> ret;        int i = len1 -1, j = len2-1, addition = 0;        while(i >=0 && j>=0){            int t1 = a[i] - '0', t2 = b[j] - '0';            int temp = t1 ^ t2 ^ addition;            addition = (t1 + t2 + addition >= 2) ? 1:0;            ret.push_back(temp);            i--;            j--;        }        if(i >= 0){            while(i>=0){                int t1 = a[i] - '0';                int temp = t1 ^ addition;                addition =( addition + t1 >=2 )?1:0;                ret.push_back(temp);                i--;            }        }        if(j >= 0){            while(j>=0){                int t2 = b[j] - '0';                int temp = t2 ^ addition;                addition =( addition + t2 >=2 )?1:0;                ret.push_back(temp);                j--;            }        }        if(addition>0)            ret.push_back(1);        string R;        for(int k = ret.size() - 1;k>=0;k--){            R += (ret[k] + '0');        }        return R;    }};


0 0