LeetCode67. Add Binary

来源:互联网 发布:大数据运用的案例 编辑:程序博客网 时间:2024/05/12 17:46

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) {        int sa = a.size();        int sb = b.size();        int flag = 0,da = 0;        string res;        for (sa,sb;sa>0 && sb > 0;sa--,sb--)        {            int temp = (int)(a[sa-1]-'0') + (b[sb-1]-'0')+flag;            flag = temp / 2;            da = temp % 2;            res.push_back(da+'0');        }        while (sa)        {            int temp = (int)(a[sa-1]-'0')+flag;            flag = temp / 2;            da = temp % 2;            res.push_back(da+'0');            sa--;        }        while (sb)        {            int temp = (int)(b[sb-1]-'0')+flag;            flag = temp / 2;            da = temp % 2;            res.push_back(da+'0');            sb--;        }        if (flag == 1)          res.push_back(flag+'0');        reverse(res.begin(),res.end());        return res;    }};
0 0
原创粉丝点击