Add Binary
Apr 2 '12
5763 / 16556
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100".
我的丑陋的
public class Solution {
public String addBinary(String a, String b) {
if(a==null||b==null) return null;
int la = a.length(),lb = b.length();
int add = 0;
int i = la-1,j=lb-1;
StringBuilder sb = new StringBuilder();
while(i>=0 && j>=0){
int sum =( a.charAt(i)-'0')
+b.charAt(j)-'0'+add;
add = sum/2;
sum = sum%2;
sb.insert(0,sum+"");
i--;
j--;
}
if(i>=0){
j=i;
b=a;
}
while(j>=0){
int sum = b.charAt(j)-'0'+add; //
add = sum/2;
sum = sum%2;
sb.insert(0,sum+"");
j--;
}
if(add>0){
sb.insert(0,"1"); //
}
return sb.toString();
}
}
别人的比较优美的写法
class Solution {
public:
string addBinary(string a, string b) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int la = a.size();
int lb = b.size();
string sum = la > lb ? a : b;
int overflow = 0;
for( int i = 0; i < sum.size(); i ++ )
{
char ca = i < la ? a[la - i - 1] : '0';
char cb = i < lb ? b[lb - i - 1] : '0';
int bit = ca - '0' + cb - '0' + overflow;
overflow = bit / 2;
sum[sum.size() - i - 1] = bit % 2 + '0';
}
if(overflow)
{
sum = "1" + sum;
}
return sum;
}
};