1. 程式人生 > >陣列和字串//二進位制求和

陣列和字串//二進位制求和

給定兩個二進位制字串,返回他們的和(用二進位制表示)。

輸入為非空字串且只包含數字 1 和 0

示例 1:

輸入: a = "11", b = "1"
輸出: "100"

示例 2:

輸入: a = "1010", b = "1011"
輸出: "10101"
class Solution {
    public String addBinary(String a, String b) {
        if(a == null || a.length() == 0)
            return b;
        if(b == null || b.length() == 0)
            return a;
        int i = a.length()-1;
        int j = b.length()-1;
        int carry = 0;
        StringBuilder sb = new StringBuilder();
        while(i >= 0 || j >= 0 || carry != 0){
            if(i >= 0){
                carry += a.charAt(i)-'0';
                i--;
            }
            if(j >= 0){
                carry += b.charAt(j)-'0';
                j--;
            }
            sb.append(carry%2);
            carry/=2;
        }
        return sb.reverse().toString();
    }
}
class Solution {
public:
    string addBinary(string a, string b) {
        int len1 = a.size();
        int len2 = b.size();
        if(len1 == 0)
            return b;
        if(len2 == 0)
            return a;
        string res;
        int carry = 0;
        int index1 = len1 - 1;
        int index2 = len2 - 1;
        while(index1 >= 0 && index2 >= 0){
            int num = (a[index1]-'0')+(b[index2]-'0')+carry;
            carry = num/2;
            num = num%2;
            index1--;
            index2--;
            res.insert(res.begin(),num+'0');
        }
        if(index1 < 0 && index2 < 0){
            if(carry == 1){
                res.insert(res.begin(),carry+'0');
                return res;
            }
        }
        while(index1 >= 0){
            int num = (a[index1]-'0')+carry;
            carry = num/2;
            num = num%2;
            index1--;
            res.insert(res.begin(),num+'0');
        }
        while(index2 >= 0){
            int num = (b[index2]-'0')+carry;
            carry = num/2;
            num = num%2;
            index2--;
            res.insert(res.begin(),num+'0');
        }
        if(carry == 1)
            res.insert(res.begin(),carry+'0');
        return res;
    }
};