Add Binary

題目:

 

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

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

思路:

兩個二進制位和進位相加的的結果有4種(0,1,2,3),所以只要兩個字符串都逐位從最後一位往前遍歷,並用一個變量保存進位,然後對三者相加結果進行相應處理即可,最後對相加得到的字符串逆序輸出即可,具體細節見代碼吧。

public String addBinary(String a, String b) {
        if (a == null || b == null || a.length() == 0 || b.length() == 0) {
            return null;
        }
        int i = a.length() - 1,j = b.length() - 1;
        int temp,k = 0;
        StringBuilder stringBuilder = new StringBuilder();
        //下面和歸併排序的Merge部分有點像
        while (i >= 0 && j >= 0) {
            temp = a.charAt(i--) - '0' + b.charAt(j--) - '0' + k;
            if (temp == 0 || temp == 1) {
                stringBuilder.append(temp);
                k = 0;
            } else {
                if (temp == 2) {
                    stringBuilder.append(0);
                    k = 1;
                } else {
                    stringBuilder.append(1);
                    k = 1;
                }
            }
        }
        while (i >= 0) {
            temp = a.charAt(i--) - '0' + k;
            if (temp  == 0 || temp == 1) {
                stringBuilder.append(temp);
                k = 0;
            } else {
                stringBuilder.append(0);
                k = 1;
            }
        }
        while (j >= 0) {
            temp = b.charAt(j--) - '0' + k;
            if (temp  == 0 || temp == 1) {
                stringBuilder.append(temp);
                k = 0;
            } else {
                stringBuilder.append(0);
                k = 1;
            }
        }
        //如果最後還有進位
        if (k == 1) {
            stringBuilder.append(1);
        }
        return stringBuilder.reverse().toString();//逆序輸出
    }

再補充個Python寫的簡潔些的版本吧

class Solution(object):
    def addBinary(self, a, b):
        """
        :type a: str
        :type b: str
        :rtype: str
        """
        i = len(a) - 1
        j = len(b) - 1
        carry = 0
        c = ''
        while i >= 0 or j >= 0 or carry > 0:
            temp = 0
            if i >= 0:
                temp += int(a[i])
                i -= 1
            if j >= 0:
                temp += int(b[j])
                j -= 1
            temp += carry
            if temp == 0:
                c = '0' + c
                carry = 0
            elif temp == 1:
                c = '1' + c
                carry = 0
            elif temp == 2:
                c = '0' + c
                carry = 1
            else:
                c = '1' + c
                carry = 1
        return c

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章