❌

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

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:

  1. Add numbers from end to start so, initials i =a.length() -1 and j=a.length()-1.
  2. Intialize the carry =0 as the remaining number.
  3. use Stringbuffer for the mutable property in string.
  4. 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.
  5. 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();

Reference :

  1. https://leetcode.com/problems/add-binary/description/

❌
❌