Add Binary Java Solution - The Coding Shala

Home >> Interview Questions >> Add Binary

Add Binary

Problem:

Given two binary strings, return their sum (also a binary string).



The input strings are both non-empty and contain only characters 1 or 0.



Example 1:

Input: a = "11", b = "1"
Output: "100"
Example 2:

Input: a = "1010", b = "1011"
Output: "10101"

Add Binary Java Solution

Approach:

Traverse from backward both string and check carry.

Java: 

class Solution {
    public String addBinary(String a, String b) {
        String ans = "";
        int len1 = a.length()-1;
        int len2 = b.length()-1;
        if(len1<0 && len2<0) return "0";
        int carry = 0;
        while(len1>=0 || len2>=0){
            int tmp = carry;
            if(len1>=0) tmp += a.charAt(len1)-'0'; //take char as int from a string
            if(len2>=0) tmp += b.charAt(len2)-'0'; //take char as int from b string
            ans = tmp%2 + ans;  //add to new string after adding both char
            carry = tmp/2; //check carry
            len1--;
            len2--;
        }
        if(carry>0) ans = 1+ans; //check carry
        return ans;
    }
}



Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Java Program to Convert Binary to Decimal - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Java Program to Convert Decimal to Binary - The Coding Shala