67. 二进制求和 LeetCode-字符串

LeetCode题目:67. 二进制求和
字符串相关题目,使用栈来实现

class Solution {
    public String addBinary(String a, String b) {
        Stack<Integer> num1 = new Stack<>();
        Stack<Integer> num2 = new Stack<>();
        Stack<Integer> sum = new Stack<>();
        for (int i = 0; i < a.length(); i++) {
            num1.push(a.charAt(i) - '0');
        }
        for (int i = 0; i < b.length(); i++) {
            num2.push(b.charAt(i) - '0');
        }
        // temp用来表示进位
        int temp = 0;
        while (!num1.isEmpty() && !num2.isEmpty()) {
        	// x和y分别表示当前需要相加的两位
            int x = num1.pop();
            int y = num2.pop();
            // 此时temp的值为前一位的进位
            sum.push((x + y + temp) % 2);
            // 将temp更新为当前位相加的进位
            if (x + y + temp >= 2) {
                temp = 1;
            } else {
                temp = 0;
            }
        }
        // 将两个数字中未进行计算的位数加到结果中,不要忘了考虑上面最后计算完的进位
        while (!num1.isEmpty()) {
            int k = num1.pop();
            sum.push((k + temp) % 2);
            if (k + temp >= 2) {
                temp = 1;
            } else {
                temp = 0;
            }
        }
        while (!num2.isEmpty()) {
            int k = num2.pop();
            sum.push((k + temp) % 2);
            if (k + temp >= 2) {
                temp = 1;
            } else {
                temp = 0;
            }
        }
        // 考虑最后一位计算完的进位
        if (temp == 1) {
            sum.push(temp);
        }
        // 依次出栈,拼接结果字符串
        String result = "";
        while (!sum.isEmpty()) {
            result += sum.pop();
        }
        return result;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值