67. Add Binary

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

For example,
a = "11"
b = "1"
code

Return "100".string


public class Solution {
    public String addBinary(String a, String b) {
        if(a == null && b == null){
            return null;
        }
        if(a == null){
            return b;
        }
        if(b == null){
            return a;
        }
        int lenA = a.length();
        int lenB = b.length();
        int len = Math.max(lenA, lenB);
        int carry = 0;
        String result = "";
        for(int i=0; i<len; i++){
            int p, q = 0;
            if(i < lenA){
                p = a.charAt(lenA-1-i) - '0'; //把字符轉換成數字,從最末尾開始讀
            }else{
                p = 0;
            }
            if(i < lenB){
                q = b.charAt(lenB-1-i) - '0';
            }else{
                q = 0;
            }
            int tem = p + q + carry;
            carry = tem/2;
            result = tem%2 + result; //不能寫成result += tem%2,順序不同
        }
        if(carry == 1){
            result = "1" + result;
        }
        return result;
    }
}
相關文章
相關標籤/搜索