Java Interview Questions - Binary Addition

Topic: Input two binary strings, calculate their sum, and output it as a binary string. For example, if the input binary strings are "11" and "10", the output will be "101".

For many people, the first thing that comes to mind when they see this question is that I first convert binary to decimal, and then convert it to binary after the operation. Although this idea is feasible, this question does not limit the length of binary. When the string is too long, it will cause integer overflow. But if we directly perform binary operations, we can not only improve efficiency, but also get better results. Avoid spills.

public String addBinary(String a,String b){
    StringBuilder result = new StringBuilder();
    int i = a.length() - 1;//从后向前加
    int j = b.length() - 1;//从后向前加
    int carry = 0; //进位表示
    while (i >= 0 || j >= 0){
        int digitA = i >= 0 ? a.charAt(i--) - '0' : 0;//判定a的值为1或者零
        int digitB = j >= 0 ? j.charAt(i--) - '0' : 0;//判定b的值为1或者零
        int sum = digitA + digitB + carry;
        carry = sum >= 2 ? 1 : 0;
        sum = sum >= 2 ? sum - 2 ; sum;
        result.append(sum);
    }
    if(carry == 1){
        result.append(1);//判断最后是否有进位
    }
    return result.reverse().toString();
}

Addition starts at the rightmost end of the string, and the lowest bit is stored at the leftmost end, so we flip that.

Guess you like

Origin blog.csdn.net/lijingxiaov5/article/details/122185687