Cover image for Classic 150 Interview Questions P67 Add Binary

Classic 150 Interview Questions P67 Add Binary


Timeline

Timeline

2025-11-25

init

Bit manipulation

Problem:

Note the final carry

12345678910111213141516171819202122232425262728293031323334353637383940414243
#include <string>#include <algorithm>using std::string;class Solution {    public:	string addBinary(string a, string b)	{		int i = a.size() - 1, j = b.size() - 1;		int carry = 0;		int curr_a_bit, curr_b_bit, curr_sum;		string res;		while (i >= 0 || j >= 0) {			if (i < 0) {				curr_a_bit = 0;			} else {				curr_a_bit = a[i] - '0';				i--;			}			if (j < 0) {				curr_b_bit = 0;			} else {				curr_b_bit = b[j] - '0';				j--;			}			curr_sum = carry + curr_a_bit + curr_b_bit;			carry = curr_sum / 2;			res.push_back('0' + curr_sum % 2);		}		if (carry == 1) {			res.push_back('1');		}		std::reverse(res.begin(), res.end());		return res;	}};int main(){	Solution S;	S.addBinary("11", "1");}
Loading comments…