67. Add Binary
This problem is like add String number in String.
Description :
Given two binary stringsΒ a
Β andΒ b
, returnΒ their sum as a binary string.
Example 1:
Input: a = "11", b = "1" Output: "100"
Example 2:
Input: a = "1010", b = "1011" Output: "10101"
Algorithm:
- Add numbers from end to start so, initials i =a.length() -1 and j=a.length()-1.
- Intialize the carry =0 as the remaining number.
- use Stringbuffer for the mutable property in string.
- Now Add the continuously,
- carry += num1.charAt(i) and iβ upto i>=0.
- carry += num2.charAt(j) and jβ upto j>=0.
- stringBuffer. append(carry%10).
- carry /= 10.
- then reverse the stringBuffer by st.reverse().
Code :
int carry =0,i=a.length()-1,j=b.length()-1; StringBuffer sb =new StringBuffer(); while(i>=0 || j>=0 || carry > 0) { if(i>=0) carry += a.charAt(i--)-'0'; if(j>=0) carry += b.charAt(j--)-'0'; sb.append(carry%2); carry /=2; } return sb.reverse().toString();