67 Binary Sum (Analog)

1. Problem description:

Given two binary strings, return their sum (in binary).

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

Example 1:

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

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

Source: LeetCode
Link: https://leetcode-cn.com/problems/add-binary

2. Thinking analysis:

① The problem is easy to understand. What we need to solve is what is the result of the two strings under the binary summation. What is easier to think of is to use the simulation method to solve, traverse the two strings from the end of the string. The loop is executed only when the lengths of the two strings are the same. After the loop ends, if the length of the string is not 0, then the remaining strings can be processed. Starting from the last character of the string, the characters are added. Operation, when adding analog and digital, you need to use variables to record the last carry, which can be divided into three cases:

1) There is a carry, and the current two characters are 1, for example, 11 + 11, the high order of both strings is 1 and there is a carry from the low order, the current calculation result of the high order is 1

2) There is a carry, and the current two characters are not all 1, such as 11 + 01, the current calculation result of the high bit is 0

3) No carry

After calculating the calculation result of the current character, we need to update the carry variable corresponding to these three situations so that the next time we add the carry

② Up to two short strings of addition can be processed in the loop, so there may be some strings that are relatively long, so we need to process the remaining strings. At this time, we need to consider the last carry and use the loop. Add the last carry to the next character, and then add the remaining characters to the result set, and get the final need to determine whether there is a carry because after the length of the string is zero, then there may be a carry At this time, add the result to the carry 1

③ If the two strings are the same length, only the last carry need be considered

④ Because there may be a string remaining, you can use a method to deal with the case where the two strings are different

⑤ When writing the code, some details may not be taken into account, so use the debug of the idea to debug the error when submitting it. So you can quickly find the error and improve efficiency. It is best not to use the API in java to solve it. Because some abnormal situations may occur

3. The code is as follows:

import java.util.Scanner;
public class Solution {
    public String addBinary(String a, String b) {
        StringBuffer res = new StringBuffer("");
        /*思路是遍历字符串模拟加法操作*/
        int aPos = a.length() - 1;
        int bPos = b.length() - 1;
        /*进位标志*/
        int isTwo = 0;
        while (aPos >= 0 && bPos >= 0){
            int aNum = a.charAt(aPos) - '0';
            int bNum = b.charAt(bPos) - '0';
            /*是否进位了, 使用if判断当前上是否进位了*/
            if (isTwo + aNum + bNum == 2){
                isTwo = 1;
                //表示进位了
                res.append('0');
            }else if (isTwo + aNum + bNum == 3){
                //表示进位了
                isTwo = 1;
                res.append('1');
            }else {
                /*相加为0或者是1的情况*/
                res.append(isTwo + aNum + bNum);
                isTwo = 0;
            }
            /*字符串往前移动一位*/
            aPos--;
            bPos--;
        }
        /*可能剩余还有字符串存在着三种情况分别是a字符串还有剩余, b字符串还有剩余, 都没有剩余*/
        if (aPos >= 0){
            return solve(res, aPos, a, isTwo);
        }else if (bPos >= 0){
            return solve(res, bPos, b, isTwo);
        }
        if (isTwo == 1) return res.append('1').reverse().toString();
        return res.reverse().toString();
    }

    private String solve(StringBuffer res, int pos, String s, int isTwo) {
        /*字符串有剩余*/
        while (pos >= 0){
            if (isTwo + (s.charAt(pos) - '0') == 2){
                res.append('0');
                isTwo = 1;
            }else {
                res.append(isTwo + (s.charAt(pos) - '0'));
                isTwo = 0;
            }
            --pos;
        }
        if (isTwo == 1) res.append('1');
        return res.reverse().toString();
    }
}

 

Published 569 original articles · Like 153 · Visits 590,000+

Guess you like

Origin blog.csdn.net/qq_39445165/article/details/105276525
67