我是靠谱客的博主 危机导师,最近开发中收集的这篇文章主要介绍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;
    }
}

最后

以上就是危机导师为你收集整理的67. 二进制求和 LeetCode-字符串的全部内容,希望文章能够帮你解决67. 二进制求和 LeetCode-字符串所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(124)

评论列表共有 0 条评论

立即
投稿
返回
顶部