Add Binary Java Solution - The Coding Shala

Home >> Interview Questions >> Add Binary

Add Binary


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


Traverse from backward both string and check carry.


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
        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.


Popular Posts from this Blog

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

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala