1. 程式人生 > >LeetCode——二進位制求和

LeetCode——二進位制求和

 

string addBinary(string a, string b) {
        int a_length = a.size();
        int b_length = b.size();
         if(a_length==0)
            return b;
        if(b_length==0)
            return a;
        //定義 閱讀可跳過
        int c_length = max(a_length, b_length) + 1;
        string c(c_length, '0');
        
        int a_bit = a_length - 1;
        int b_bit = b_length - 1;
        int c_bit = c_length - 1;
        
        int a_value   = 0;
        int b_value   = 0;
        int bit_value = 0; 
        int carry = 0;
        //邏輯從此開始
        while(a_bit >= 0 || b_bit >= 0)
        {
            a_bit < 0 ? a_value = 0 : a_value = a[a_bit] - '0';
            b_bit < 0 ? b_value = 0 : b_value = b[b_bit] - '0';
            bit_value = a_value + b_value  + carry;
            carry = bit_value / 2;
            c[c_bit] = bit_value % 2 + '0';
            if(a_bit >= 0)  --a_bit;
            if(b_bit >= 0)  --b_bit;
            --c_bit;
        }
        if(carry)
        {
            c[c_bit] = '1';
            return c;
        }
        else
            return c.substr(1,c_length - 1);