标签:style blog color io ar for sp div c
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 };
标签:style blog color io ar for sp div c
原文地址:http://www.cnblogs.com/bugfly/p/4008756.html