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

The input strings are both non-empty and contains only characters 1 or 0.

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

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

难度: easy

题目:
给定两个二进制字符串,返回它们的和(也是二进制字符串)。
字符串都不为空且只有0、1组成。

Runtime: 2 ms, faster than 95.70% of Java online submissions for Add Binary.
Memory Usage: 26.2 MB, less than 54.54% of Java online submissions for Add Binary.

public class Solution {
    public String addBinary(String a, String b) {
        int i = a.length() - 1, j = b.length() - 1, carry = 0;
        StringBuilder result = new StringBuilder();
        while (i >= 0 || j >= 0) {
            char ac = i >= 0 ? a.charAt(i) : '0';
            char bc = j >= 0 ? b.charAt(j) : '0';
            
            int sum = (ac - '0') + (bc - '0') + carry;
            result.append(sum % 2);
            carry = sum / 2;
            i--;
            j--;
        }
        
        if (carry > 0) {
            result.append(1);
        }
        
        return new String(result.reverse());
    }
}

linm
1 声望4 粉丝

〜〜〜学习始于模仿,成长得于总结〜〜〜


下一篇 »
69. Sqrt(x)