示例 1:
输入:a = “11”, b = “1”
输出:“100”
示例 2:
输入:a = “1010”, b = “1011”
输出:“10101”
逐位相加再进位:
public class AddBinary {
public String addBinary(String a, String b) {
StringBuilder result = new StringBuilder();
int i = a.length() - 1, j = b.length() - 1, carry = 0;
while (i >= 0 || j >= 0) {
//值
int sum = carry;
if (i >= 0) sum += a.charAt(i--) - '0';
if (j >= 0) sum += b.charAt(j--) - '0';
result.append(sum % 2);
//进位
carry = sum / 2;
}
if (carry != 0) result.append(carry);
return result.reverse().toString();
}
// 测试用例
public static void main(String[] args) {
AddBinary solution = new AddBinary();
System.out.println(solution.addBinary("11", "1")); // 期望输出: "100"
System.out.println(solution.addBinary("1010", "1011")); // 期望输出: "10101"
}
}