leetcode--Add Binary

来源:互联网 发布:js 变量给数组赋值 编辑:程序博客网 时间:2024/05/31 18:51

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

Have you been asked this question in an interview? 

Discuss


class Solution {public:    string addBinary(string a, string b)     {        int lena = a.size();        int lenb = b.size();        int i,j;        if(lena==0||lenb==0)return a+b;        string str;        int carry = 0;        int tem;        for(i=lena-1, j=lenb-1;i>=0&&j>=0;i--,j--)        {            tem   = (a[i]+b[j]+carry-2*'0')%2;            carry = (a[i]+b[j]+carry-2*'0')/2;            str = (char)(tem + '0') + str;                    }        if(i>=0)        {            while(i!=-1)            {                                 tem   = (a[i]+carry-'0')%2;                carry = (a[i]+carry-'0')/2;                str = (char)(tem + '0') + str;                 i--;            }        }        if(j>=0)        {            while(j!=-1)            {                           tem   = (b[j]+carry-'0')%2;            carry = (b[j]+carry-'0')/2;            str = (char)(tem + '0') + str;             j--;            }        }        if(carry==1)            str = '1'+str;        return str;    }};


0 0
原创粉丝点击