LeetCode Add Binary Final Report and leetcode Final Report
Https://oj.leetcode.com/problems/add-binary/
Given two binary strings, return their sum (also a binary string ).
For example,
A = "11"
B = "1"
Return "100 ".
Solution Report: Binary addition, which is classified as Easy. There is no algorithm, that is, it can be calculated according to a common method.
At the beginning, I wrote a high/low reverse, and then added it from 0 to the high position, until the number of digits is less than the first, and then if there is a carry) perform carry operations on strings with multiple digits.
Later, it was found that reverse is not required, and the highest bit is directly calculated to the zero bit. The AC code is as follows:
public class Solution { public String addBinary(String a, String b) { StringBuffer result = new StringBuffer("");int i = a.length() - 1;int j = b.length() - 1;int carry = 0;int index = 0;int acurrent = 0;int bcurrent = 0;for(;i>=0||j>=0;i--,j--) {acurrent = i>=0? a.charAt(i) - '0' : 0;bcurrent = j>=0? b.charAt(j) - '0' : 0;int current = (acurrent + bcurrent + carry)%2;carry = (acurrent + bcurrent + carry)/2;result = result.insert(0, current);}if(carry ==1) { result.insert(0, '1'); } return result.toString(); }}