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;
}
};
Add Binary
最新推荐文章于 2022-04-09 11:43:16 发布