欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Add Binary

程序员文章站 2022-06-04 10:58:35
...

题目表述
Given two binary strings, return their sum (also a binary string).

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

分析:其实就是给定两个字符串,字符串中的值为二进制,让我们计算两个字符串中二进制相加,并返回结果。

我的Code如下:

class Solution {
    public String addBinary(String a, String b) {
        int maxLen = a.length();
        if (b.length() > maxLen) {
            maxLen = b.length();
        }

        // 把字符串a逆序存入数组A中
        int[] arrayA = new int[a.length()];
        for (int i = a.length() - 1; i >= 0; i--) {
            arrayA[a.length() - 1 - i] = Integer.parseInt(a.charAt(i) + "");
        }
        int[] arrayB = new int[b.length()];
        for (int i = b.length() - 1; i >= 0; i--) {
            arrayB[b.length() - 1 - i] = Integer.parseInt(b.charAt(i) + "");
        }

        int[] array = new int[maxLen + 1];
        if (a.length() > b.length()) {
            for (int i = 0; i < arrayA.length; i++) {
                if (i < b.length()) {
                    // 正常加
                    array[i] = arrayA[i] + arrayB[i] + array[i];
                } else {
                    // b没了,就剩a
                    array[i] = arrayA[i] + array[i];
                }
                if (array[i] > 1) {
                    int chu = array[i] / 2;
                    int yu = array[i] % 2;
                    array[i] = yu;
                    array[i + 1] = chu;
                }
            }
        } else {
            for (int i = 0; i < arrayB.length; i++) {
                if (i < a.length()) {
                    // 正常加
                    array[i] = arrayA[i] + arrayB[i] + array[i];
                } else {
                    array[i] = arrayB[i] + array[i];
                }
                if (array[i] > 1) {
                    int chu = array[i] / 2;
                    int yu = array[i] % 2;
                    array[i] = yu;
                    array[i + 1] = chu;
                }
            }
        }

        // 倒序输出array即可
        String str = "";
        for (int i = array.length - 1; i >= 0; i--) {
            if (i == array.length - 1) {
                if (array[i] == 0) {
                    continue;
                }
            }
            str += array[i] + "";
        }

        return str;
    }
}