67. Add Binary

Given two binary strings, return their sum (also a binary string).

For example,
a = "11"
b = "1"
Return "100".

和415的解法一样

class Solution {

    public String addBinary(String a, String b) {

        StringBuilder sb = new StringBuilder();

        int i = a.length() - 1;

        int j = b.length() - 1;

        int carry = 0;

        for(; i >= 0 || j >= 0 || carry == 1; i--, j--){

            int x = i < 0 ? 0 : a.charAt(i) - '0';

            int y = j < 0 ? 0 : b.charAt(j) - '0';

            sb.append((x + y + carry) % 2); //除去进位后的值 

            carry = (x + y + carry) / 2; //算出进位值

        }

        return sb.reverse().toString();

    }

}

上一篇:leetcode371 两整数之和 python


下一篇:Add to Array-Form of Integer LT989