Skip to main content

Leetcode 67 - Add Binary (Easy) - C++ Code With Explanation

Leetcode 67 - Add Binary (Easy)

Problem- https://leetcode.com/problems/add-binary/

Approach-

In normal addition, we start from the least significant position i.e. from right to left. So to perform this in the strings we have to reverse both the strings. After the reversal, we have to make their length equal by adding the character '0' to the smaller string. Now perform the addition process starting from the left-hand side in the reversed and equal lengthed strings using the carry method. Initially carry is 0 and the further cases are explained in the code. In binary addition sum of 1 and 1 gives 0 with carry 1. And the sum of 1 and 1 with carry one gives 1 as result along with carry 1.

Another method that we can use is to convert both the strings in decimal form and then add them and return the binary form string of the resultant addition in decimal form.

Below is the code for the same.

Code-

string addBinary(string a, string b) { reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); int n=a.length(); int m=b.length(); if(n<m) { int c=m-n; while(c>0) { a+='0'; c--; } n=m; } if(n>m) { int c=n-m; while(c>0) { b+='0'; c--; } m=n; } int j=0, carry=0; string ans=""; while(j<n) { if(a[j]=='1'&&b[j]=='1'&&carry==1) { ans+='1'; carry=1; } else if(a[j]=='1'&&b[j]=='1'&&carry==0) { ans+='0'; carry=1; } else if(a[j]=='1'&&b[j]=='0'&&carry==0) { ans+='1'; carry=0; } else if(a[j]=='1'&&b[j]=='0'&&carry==1) { ans+='0'; carry=1; } else if(a[j]=='0'&&b[j]=='1'&&carry==0) { ans+='1'; carry=0; } else if(a[j]=='0'&&b[j]=='1'&&carry==1) { ans+='0'; carry=1; } else if(a[j]=='0'&&b[j]=='0'&&carry==1) { ans+='1'; carry=0; } else if(a[j]=='0'&&b[j]=='0'&&carry==0) { ans+='0'; carry=0; } j++; } if(carry==1) ans+='1'; reverse(ans.begin(), ans.end()); return ans; }