[LeetCode-Java Exercise] 67. Binary Sum (Simple)

1. Title description

Insert picture description here

2. Problem solving ideas

The overall idea is to fill the shorter two strings with 0 to make the two strings have the same length, and then traverse the calculation from the end to get the final result.
Due to string manipulation reasons, it is uncertain whether the final result will have one more carry, so there are two processing methods: the
first is to directly concatenate the string during the calculation, and you will get a reverse character, which needs to be repeated at the end Carrying over the
second type, assign the result character according to the position, and finally if there is a carry, then perform string splicing in the front to add the carry

3. Code implementation

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();
    }

Guess you like

Origin blog.csdn.net/weixin_48683410/article/details/113874708