LeetCode 67. Binary sum (Java)

67. The binary sum

Given two binary string, and return to their (expressed in binary).
And a non-empty input string contains only numbers 0 and 1.

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

Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/add-binary
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.

Thinking: two strings of short length to par 0s less, and from the low-order calculations, successively fill in the new string, if the final carry, and then end up in a 1, the output of the whole to reverse a string can be.

class Solution {
    public String addBinary(String a, String b) {
        StringBuilder res=new StringBuilder();
        int carray=0;
        for(int i=a.length()-1,j=b.length()-1;i>=0||j>=0;i--,j--)
        {
            int sum=carray;
            sum+=i>=0?a.charAt(i)-'0':0;
            sum+=j>=0?b.charAt(j)-'0':0;
            res.append(sum%2);
            carray=sum/2;
        }
        res.append(carray>0?1:"");
        return res.reverse().toString();
    }
}
Published 88 original articles · won praise 0 · Views 2150

Guess you like

Origin blog.csdn.net/nuts_and_bolts/article/details/105104247