Leetcode 67 Add Binary

HowieLee59發表於2018-12-11

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

The input strings are both non-empty and contains only characters 1 or 0.

Example 1:

Input: a = "11", b = "1"
Output: "100"

Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

這個題的意思就是實現一個二進位制的加法,模擬題意即可以實現

1)

class Solution {
public:
    string addBinary(string a, string b) {
        reverse(a.begin(),a.end());
        reverse(b.begin(),b.end());//首先把兩個字串逆轉
        int t = 0;
        string res = "";//計算後的字串
        for(int i = 0 ; i < a.size() || i < b.size() ;i++){
            int va = i >= a.size() ? 0 : a[i] - '0';
            int vb = i >= b.size() ? 0 : b[i] - '0';
            int s = va + vb + t;//標識加之後的數值
            t = s / 2;//將位置推進一位
            s %= 2;//看此位置上為0還是1
            res += to_string(s);//變為字串
        }
        if(t) res += '1';//如果還有餘數,那麼最後的時候
        return string(res.rbegin(),res.rend());//進行逆轉
    }
};

2)

class Solution {
public:
    string addBinary(string a, string b) {
        int counter1 = a.length()-1;
        int counter2 = b.length()-1;
        int carry = 0;
        string res;
        while (counter1>=0 || counter2>=0) {
            int sum = carry;
            if (counter1>=0) {
                sum += (a[counter1] - '0');
            }
            if (counter2>=0) {
                sum += (b[counter2] - '0');
            }
            res.append(to_string(sum % 2));
            carry = sum / 2;
            counter1--;
            counter2--;
        }
        if (carry != 0) res.append(to_string(carry));
        
        int n = res.length(); 
        // Swap character starting from two 
        // corners 
        for (int i = 0; i < n / 2; i++) {
            swap(res[i], res[n - i - 1]); 
        }
        
        return res;
    }
};

 

相關文章