1. 程式人生 > >LetCode 67. 二進位制求和

LetCode 67. 二進位制求和

static int x=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return 0;
}();
class Solution {
public:
    string addBinary(string a, string b) {
	    int len_a = a.length();
	    int len_b = b.length();
        // 新建一個結果字串,長度為a、b串中最長的一個加1,加的一位留給進位
	    int len = max(len_a, len_b);
	    string res(len + 1, '0');
	    int i = len_a - 1, j = len_b - 1;
	    int index = len;
	    int carry = 0;
        // 模擬手算
	    while (index >= 0) {
		    res[index] = (i >= 0 ? a[i] : '0') + (j >= 0 ? b[j] : '0') + carry - 48;
		    carry = (res[index] - 48) / 2;
		    res[index] = (res[index] - 48) % 2 + 48;
		    index--;
		    i--;
		    j--;
	    }
	    index = 0;
        // 找到第一個不為0的位置
	    while (res[index] == '0' && index <= len) index++;
        // 如果結果為0,就直接返回0
        if (index == len + 1)
		    return "0";
	    return res.substr(index);
    }
};