aboutsummaryrefslogtreecommitdiff
path: root/add_binary.cpp
blob: 9afc1dcd3927387e9221188ac1ba5029ef14d2c6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 67. Add Binary
#include "leetcode.h"

class Solution {
public:
  string addBinary(string a, string b) {
    int i = a.size() - 1, j = b.size() - 1, carry = 0;
    string ans;
    while (i >= 0 || j >= 0 || carry) {
      if (i >= 0) {
        carry += a[i] - '0';
        i--;
      }
      if (j >= 0) {
        carry += b[j] - '0';
        j--;
      }
      ans += (carry % 2 + '0');
      carry /= 2;
    }
    reverse(ans.begin(), ans.end());
    return ans;
  }
};

int main() {
  Solution obj;
  cout << obj.addBinary("11", "1") << endl;      // expect: 100
  cout << obj.addBinary("1010", "1011") << endl; // expect: 10101
}