Leetcode brushing questions --- string --- binary summation

Give you two binary strings and return their sum (in binary representation).

The input is a non-empty string and contains only the numbers 1 and 0.

Example 1:

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

Example 2:

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

prompt:

每个字符串仅由字符 '0' 或 '1' 组成。
1 <= a.length, b.length <= 10^4
字符串如果不是 "0" ,就都不含前导零。

Source: LeetCode (LeetCode) Link: https://leetcode-cn.com/problems/add-binary
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.

See a good way of writing in the comment area

class Solution {
    
    
    public String addBinary(String a, String b) {
    
    
        int i = a.length() - 1;
        int j = b.length() - 1;
        int carry = 0;
        StringBuilder builder = new StringBuilder();
        //循环相加两个字符串相同长度的低位数部分
        while (i >= 0 && j >= 0) {
    
    
            int sum = carry;
            sum += a.charAt(i--) - '0';
            sum += b.charAt(j--) - '0';
            carry = sum / 2;
            builder.append(sum % 2);
        }
        // 如果 a 还没遍历完成(a串比b串长),则继续遍历添加 a 的剩余部分
        while (i >= 0) {
    
    
            int sum = carry + a.charAt(i--) - '0';
            carry = sum / 2;
            builder.append(sum % 2);
        }
        // 如果 b 还没遍历完成(b串比a串长),则继续遍历添加 b 的剩余部分
        while (j >= 0) {
    
    
            int sum = carry + b.charAt(j--) - '0';
            carry = sum / 2;
            builder.append(sum % 2);
        }
        //如果 carry 不等于0 还有个进位数没加进去,需要补充
        if (carry == 1) {
    
    
            builder.append(carry);
        }
        //反转字符串获得正常结果
        return builder.reverse().toString();
    }

What needs to be understood here is that the ASCII code of 1 is used to be exactly 1 greater than 0. Through this we can directly fill the value into the sum. In addition, the final need to be reversed is because we fill in the StringBuilder gradually by low-level calculations, and finally The result is a high start, so it needs to be reversed.

Guess you like

Origin blog.csdn.net/weixin_46428711/article/details/111406837