Add Binary

来源:互联网 发布:大数据分析算法 编辑:程序博客网 时间:2024/05/13 13:54

问题描述: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 aLen = a.size();        int bLen = b.size();        int i = aLen-1;        int j = bLen-1;        int c = 0;        int num;        string result;        while(i>=0&&j>=0)        {            num = a[i]-'0'+b[j]-'0'+c;            c = num/2;            num = num%2;            result = char(num+'0')+result;//此处的想法比较关键,用一个字符串的加法从后向前添加字符。            i--;            j--;        }        while(i>=0)        {            num = char(a[i]-'0')+c;            c = num/2;            num=num%2;            result = char(num+'0')+result;            i--;        }        while(j>=0)        {            num =b[j]-'0'+c;            c = num/2;            num=num%2;            result = char(num+'0')+result;            j--;        }        if(c>0)        {            result = '1'+result;        }        return result;    }};
0 0
原创粉丝点击