Add Binary Solutions in C++
Number 67
Difficulty Easy
Acceptance 45.3%
Link LeetCode
Other languages Go
Solutions
C++ solution by haoel/leetcode
// Source : https://oj.leetcode.com/problems/add-binary/// Author : Hao Chen// Date : 2014-07-05#include <iostream>#include <string>using namespace std;string addBinary(string a, string b) {int alen = a.size();int blen = b.size();bool carry = false;string result;while( alen>0 || blen>0) {int abit = alen<=0 ? 0 : a[alen-1]-'0';int bbit = blen<=0 ? 0 : b[blen-1]-'0';int cbit = carry ? 1 : 0;result.insert(result.begin(), '0' + ((abit+bbit+cbit) & 1) );carry = (abit+bbit+cbit>1);alen--; blen--;}if (carry){result.insert(result.begin(), '1');}return result;}int main(int argc, char** argv){string a = "11";string b = "1";if (argc>2){a = argv[1];b = argv[2];}cout << a << "+" << b << "=" << addBinary(a, b) << endl;}
C++ solution by pezy/LeetCode
#include <string>using std::string;class Solution {public:string addBinary(string a, string b) {string ret;bool carry{false};for (auto apos=a.size(), bpos=b.size(); apos || bpos || carry; ) {bool abit{apos && a[--apos] == '1'};bool bbit{bpos && b[--bpos] == '1'};ret = (abit ^ bbit ^ carry ? "1" : "0") + ret;carry = abit + bbit + carry >= 2;}return ret;}};
C++ solution by liuyubobobo/Play-Leetcode
/// Source : https://leetcode.com/problems/add-binary/description//// Author : liuyubobobo/// Time : 2018-06-03#include <iostream>using namespace std;/// Simulation/// Time Complexity: O(max(len(a), len(b)))/// Space Complexity: O(1)class Solution {public:string addBinary(string a, string b) {string res = a.size() > b.size() ? a : b;string adder = a.size() > b.size() ? b : a;int index = res.size() - 1;for(int i = adder.size() - 1 ; i >= 0 ; i --){res[index] += adder[i] - '0';index --;}for(int i = res.size() - 1 ; i > 0 ; i --)if(res[i] > '1'){res[i - 1] += 1;res[i] = '0' + (res[i] - '0') % 2;}if(res[0] > '1'){res[0] = '0' + (res[0] - '0') % 2;res = '1' + res;}return res;}};int main() {cout << Solution().addBinary("11", "1") << endl;cout << Solution().addBinary("1010", "1011") << endl;return 0;}