给定字符串a,b,分别表示两个二进制数。将a,b的二进制和以字符串形式返回。
Given two binary strings, return their sum (also a binary string).
For example,
a ="11"
b ="1"
Return"100"
.
思路:模拟二进制加法过程,从最低位开始
难点在于进位的计算。记进位符为carry, 该位的和为num
int num = a[i]-'0'+b[j]-'0'+carry; carry = num/2; num %= 2;
代码
1 class Solution { 2 public: 3 string addBinary(string a, string b) { 4 // IMPORTANT: Please reset any member data you declared, as 5 // the same Solution instance will be reused for each test case. 6 string ret; 7 int i=a.length()-1, j=b.length()-1; 8 int carry = 0; 9 while(i>=0 && j>=0) 10 { 11 int num = a[i]-'0'+b[j]-'0'+carry; 12 carry = num/2; 13 num %= 2; 14 ret = char(num+'0') + ret; 15 --i; --j; 16 } 17 // add carry and remaining string 18 while(i>=0) 19 { 20 int num = a[i]-'0'+carry; 21 carry = num/2; 22 num %=2; 23 ret = char(num+'0')+ret; 24 --i; 25 } 26 while(j>=0) 27 { 28 int num = b[j]-'0'+carry; 29 carry = num/2; 30 num %=2; 31 ret = char(num+'0')+ret; 32 --j; 33 } 34 35 if(carry>0) 36 ret = "1"+ret; 37 38 return ret; 39 } 40 };