问题描述:
Add Binary
Given two binary strings, return their sum (also a binary string).
For example,
a = "11"
b = "1"
Return "100"
public class Solution {
static public char[] count(char a, char b, char tmp){
char[] re = new char[2];
if(a=='1' && b=='1'&&tmp == '1'){
re[0] = '1';
re[1] = '1';
}
if(a=='1' && b=='1'&&tmp == '0'){
re[0] = '0';
re[1] = '1';
}
if(a=='1' && b=='0'&&tmp == '1'){
re[0] = '0';
re[1] = '1';
}
if(a=='0' && b=='1'&&tmp == '1'){
re[0] = '0';
re[1] = '1';
}
if(a=='1' && b=='0'&&tmp == '0'){
re[0] = '1';
re[1] = '0';
}
if(a=='0' && b=='0'&&tmp == '1'){
re[0] = '1';
re[1] = '0';
}
if(a=='0' && b=='1'&&tmp == '0'){
re[0] = '1';
re[1] = '0';
}
if(a=='0' && b=='0'&&tmp == '0'){
re[0] = '0';
re[1] = '0';
}
return re;
}
public String addBinary(String a, String b) {
if(a.length()<b.length()){
String tmp = a;
a = b;
b = tmp;
}
char[] A = a.toCharArray();
char[] B = b.toCharArray();
String re = "";
int m = A.length;
char tmp = '0';
for(int i = m-1; i>=0; i--){
char c1,c2;
if(i<A.length - B.length){
c1 = A[i];
c2 = '0';
}else{
c1 = A[i];
c2 = B[i -(A.length - B.length)];
}
char[] s = count(c1, c2, tmp);
re = s[0] + re;
tmp = s[1];
<span style="white-space:pre"> </span>}
if(tmp=='1'){
re = '1' + re;
}
return re;
}
}