1. 程式人生 > >67. Add Binary - Easy

67. Add Binary - Easy

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"

 

從後往前加,用兩個引數,sum和remainder分別表示和、餘數。當兩個string陣列下標不越界時,sum等於兩個數相加,res append (sum % 2),餘數為 sum/2,表示進位,下一次進入迴圈時,sum就等於remainder,在此基礎上繼續累加。最後當兩個string都加完,考慮進位:如果最後的餘數為0,不進位;如果不為0,在res裡append最後一次迴圈得到的餘數。

由於append的順序和二進位制數的高低位順序是相反的,最後還要把res反轉一下

time: O(n), space: O(n)

class Solution {
    public String addBinary(String a, String b) {
        StringBuilder res = new StringBuilder();
        int i = a.length() - 1, j = b.length() - 1;
        int remainder = 0;
        while(i >= 0 || j >= 0) {
            
int sum = remainder; if(i >= 0) { sum += a.charAt(i--) - '0'; } if(j >= 0) { sum += b.charAt(j--) - '0'; } res.append(sum % 2); remainder = sum / 2; } if(remainder != 0) { res.append(remainder); }
return res.reverse().toString(); } }