Binary sum

 Binary sum


Problem Description


Write a Java program to add two binary numbers.

Logic Test Case 1


Input (stdin)

10


11


Expected Output


101

Logic Test Case 2


Input (stdin)

100


111


Expected Output


1011




Code Area


import java.io.*;

import java.util.Scanner;

public class TestClass {

public static void main(String[] args)

     { 

       long binary1,binary2;

       int i=0,remainder=0;

       int[] sum=new int[20];

       Scanner in=new Scanner(System.in);

       binary1=in.nextLong();

       binary2=in.nextLong();

       while(binary1 !=0||binary2 !=0)

       {

         sum[i++]=(int)((binary1 % 10 + binary2 % 10 +remainder)%2);

         remainder=(int)((binary1 % 10 + binary2 % 10 +remainder)/2);

         binary1=binary1/10;

         binary2=binary2/10;

       }

       if(remainder!=0)

       {

         sum[i++]=remainder;

       }

       --i;

       while(i>=0)

       {

         System.out.print(sum[i--]);

       }

       System.out.print("\n");

     }

}

Post a comment

0 Comments