
思路:从右边开始,逐位相加,包括进位。
代码:
public class AddBinary67 {
public static void main(String[] args) {
// System.out.println(addBinary("11", "1"));
System.out.println(addBinary("1", "111"));
}
public static String addBinary(String a, String b) {
Stack<Integer> stack = new Stack<>();
int i = a.length() - 1;
int j = b.length() - 1;
int bit = 0;
int tmp = 0;
while (i >= 0 && j >= 0) {
tmp = (a.charAt(i--) - '0') + (b.charAt(j--) - '0') + bit;
bit = tmp / 2;
stack.push(tmp % 2);
}
while (i >= 0) {
tmp = a.charAt(i--) - '0' + bit;
stack.push(tmp % 2);
bit = tmp / 2;
}
while (j >= 0) {
tmp = b.charAt(j--) - '0' + bit;
stack.push(tmp % 2);
bit = tmp / 2;
}
if (bit > 0)
stack.push(bit);
StringBuilder sb = new StringBuilder();
while (!stack.empty())
sb.append(stack.pop());
return sb.toString();
}
}
输出:
![]()

本文介绍了一种实现二进制数相加的算法,通过栈来逆序存储逐位相加的结果,包括处理进位的过程。算法首先将两个二进制字符串从右向左遍历,对每一位进行相加并考虑进位,最后将栈中存储的结果正序输出为字符串。
407

被折叠的 条评论
为什么被折叠?



