思路:从低位加到最高位,相加之和sum % 2;进位 carry = sum / 2;最后反向输出。
public static String addBinary(String a, String b) {
StringBuilder stringBuilder = new StringBuilder();
int carry = 0;
int i = a.length() - 1;
int j = b.length() - 1;
while(i >= 0 || j >= 0) {
int sum = carry;
if (i >= 0) {
sum += a.charAt(i--) - '0';
}
if (j >= 0) {
sum += b.charAt(j--) - '0';
}
stringBuilder.append(sum % 2);
carry = sum / 2;
}
if (carry != 0) {
stringBuilder.append(carry);
}
return stringBuilder.reverse().toString();
}
public static void main(String[] args) {
String a = "11";
String b = "1";
System.out.println(addBinary(a, b));