[LeetCode] 67. Add Binary binary sum (Easy) (JAVA)

[LeetCode] 67. Add Binary binary sum (Easy) (JAVA)

Topic Address: https://leetcode.com/problems/plus-one/

Subject description:

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"

Subject to the effect

Given two binary string, and return to their (expressed in binary).

And a non-empty input string contains only numbers 0 and 1.

Problem-solving approach

Relatively simple, direct traversal, determine the need to carry

class Solution {
    public String addBinary(String a, String b) {
        StringBuilder res = new StringBuilder();
        int carry = 0;
        for (int i = 0; i < a.length() || i < b.length(); i++) {
            if (i < a.length()) {
                carry += a.charAt(a.length() - 1 - i) - '0';
            }
            if (i < b.length()) {
                carry += b.charAt(b.length() - 1 - i) - '0';
            }
            res.append((carry % 2));
            carry /= 2;
        }
        if (carry > 0) res.append(carry);
        return res.reverse().toString();
    }
}

When execution: 3 ms, beat the 54.59% of all users to submit in Java
memory consumption: 38.2 MB, beat the 5.16% of all users to submit in Java

Published 81 original articles · won praise 6 · views 2271

Guess you like

Origin blog.csdn.net/qq_16927853/article/details/104894314