Add Binary

来源:互联网 发布:淘宝买家怎么切换卖家 编辑:程序博客网 时间:2024/04/30 01:52
class Solution {public:    string addBinary(string a, string b) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        string retString;        if( a.empty() )            return b;        else if( b.empty() )            return a;        int length = a.length() > b.length() ? a.length() : b.length();        int carry = 0 ;        for( int indx = 0 ; indx < length ; ++indx )        {            if( indx < a.length() && indx < b.length() )            {                int num = a[a.size() - indx -1 ] - '0' + b[b.size() - indx - 1 ] - '0' + carry;                carry = num/2;                                retString.push_back('0'+num%2);            }            else if( indx < a.length() && indx >= b.length() )            {                int num = a[a.size() - indx - 1] - '0' + carry;                carry = num/2;                retString.push_back('0'+num%2);            }            else if( indx < b.length() && indx >= a.length() )            {                int num = b[b.size() - indx - 1] - '0' + carry;                carry = num/2;                retString.push_back('0'+num%2);            }        }        if( carry )               retString.push_back('1');        reverse(retString.begin() , retString.end() );        if( retString.empty() )            retString.push_back('0');        return retString;            }};

原创粉丝点击