Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
.
类似模拟十进制加法
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 if( a.empty() ) return b; 5 if( b.empty() ) return a; 6 string ans; 7 reverse(a.begin(), a.end()); //反转后,从低位开始相加 8 reverse(b.begin(), b.end()); 9 int i=0; 10 int carry = 0; 11 while( i<a.length() && i<b.length() ) { //处理他们共同都有的部分 12 int sum = a[i] - '0' + b[i] - '0' + carry; 13 if( sum == 3 ) { 14 ans.push_back('1'); 15 carry = 1; 16 } else if( sum == 2 ) { 17 ans.push_back('0'); 18 carry = 1; 19 } else if( sum == 1 ) { 20 ans.push_back('1'); 21 carry = 0; 22 } else if( sum == 0 ) { 23 ans.push_back('0'); 24 carry = 0; 25 } 26 ++i; 27 } 28 string& c = a.length() > b.length() ? a : b; 29 while( i<c.length() ) { //处理一方多余的部分,及进位 30 int sum = c[i] - '0' + carry; 31 if( sum == 2 ) { 32 ans.push_back('0'); 33 carry = 1; 34 } else if( sum == 1 ) { 35 ans.push_back('1'); 36 carry = 0; 37 } else if( sum == 0 ) { 38 ans.push_back('0'); 39 carry = 0; 40 } 41 ++i; 42 } 43 if( carry ) ans.push_back('1'); //最后若有进位 44 reverse(ans.begin(), ans.end()); 45 return ans; 46 } 47 };
class Solution { public: string addBinary(string a, string b) { return addStringBaseN(a, b, 2); } string addStringBaseN(string num1, string num2, int base) { std::reverse(num1.begin(), num1.end()); std::reverse(num2.begin(), num2.end()); string sum_string; int i = 0; int carry = 0; while (i < num1.size() && i < num2.size()) { int sum = (num1[i] - '0') + (num2[i] - '0') + carry; sum_string.push_back((sum % base) + '0'); carry = sum / base; ++i; } const string& lstring = num1.size() > num2.size() ? num1 : num2; while (i < lstring.size()) { int sum = lstring[i] - '0' + carry; sum_string.push_back(sum % base + '0'); carry = sum / base; ++i; } if (carry > 0) { sum_string.push_back(carry + '0'); } std::reverse(sum_string.begin(), sum_string.end()); return sum_string; } };