Add Two Binary Numbers in Java

Write a program in Java to add two binary numbers (without decimal points) without converting them into decimal numbers. The numbers are to be input by the user.

Binary numbers are the numbers which have base (or radix) 2 because it consists of only two digits, zeroes and ones.

Example:
INPUT:
First number: 101
Second number: 11
OUTPUT:
Sum = 1000

import java.io.*;
class Sum{
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("First binary number: ");
        String a = br.readLine();
        System.out.print("Second binary number: ");
        String b = br.readLine();
        if(!validate(a) && !validate(b)){
            System.out.println("Invalid binary value!");
            return;
        }
        String result = add(a, b);
        System.out.println("Sum = " + result);
    }
    public static boolean validate(String n){
        for(int i = 0; i < n.length(); i++){
            char ch = n.charAt(i);
            if(ch != '0' && ch != '1')
                return false;
        }
        return true;
    }
    public static String add(String a, String b){
        while(a.length() < b.length())
            a = "0" + a;
        while(b.length() < a.length()) 
            b = "0" + b;
        int carry = 0;
        String result = ""; 
        for(int i = a.length() - 1; i >= 0; i--){
            int d1 = Integer.parseInt(Character.toString(a.charAt(i)));
            int d2 = Integer.parseInt(Character.toString(b.charAt(i)));
            int sum = d1 + d2 + carry;
            if(sum == 0)
                result = "0" + result;
            else if(sum == 1){
                result = "1" + result;
                carry = 0;
            }
            else if(sum == 2){
                result = "0" + result;
                carry = 1;
            }
            else if(sum == 3){
                result = "1" + result;
                carry = 1;
            }
        }
        if(carry == 1)
            result = "1" + result;
        return result;
    }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.