Binary Addition
Input 1st no. 1010
Input 2nd no. 111
Sum = 10001
import java.io.*;
public class Binary_Add
{
public static void main(String ss[]) throws IOException
{
InputStreamReader x=new InputStreamReader(System.in);
BufferedReader y=new BufferedReader(x);
System.out.println(“Input 1st no.”);
String s1=y.readLine();
s1=”0″+s1;
System.out.println(“Input 2nd no.”);
String s2=y.readLine();
s2=”0″+s2;
int l1,l2,sum=0,max=0,j,c;
l1=s1.length(); l2=s2.length();
String add=””;
int sm=0, cr=0;
if(l1==l2)
max=l1;
if(l1>l2)
{
max=l1;
c=l1-l2;
for(j=1;j<=c;j++)
s2=”0″+s2;
}
if(l2>l1)
{
max=l2;
c=l2-l1;
for(j=1;j<=c;j++)
s1=”0″+s1;
}
for(int i=max-1;i>=0;i–)
{
char ch1=s1.charAt(i);
char ch2=s2.charAt(i);
sum=Integer.parseInt(Character.toString(ch1))+Integer.parseInt(Character.toString(ch2))+cr;
if(sum==0)
{ sm=0; cr=0; }
if(sum==1)
{ sm=1; cr=0; }
if(sum==2)
{ sm=0; cr=1; }
if(sum==3)
{
sm=1; cr=1; }
String temp=Integer.toString(sm);
add=temp+add;
}
System.out.println(“Sum = “+add);
}
}
Input 1st no. 1010
Input 2nd no. 111
Sum = 10001
import java.io.*;
public class Binary_Add
{
public static void main(String ss[]) throws IOException
{
InputStreamReader x=new InputStreamReader(System.in);
BufferedReader y=new BufferedReader(x);
System.out.println(“Input 1st no.”);
String s1=y.readLine();
s1=”0″+s1;
System.out.println(“Input 2nd no.”);
String s2=y.readLine();
s2=”0″+s2;
int l1,l2,sum=0,max=0,j,c;
l1=s1.length(); l2=s2.length();
String add=””;
int sm=0, cr=0;
if(l1==l2)
max=l1;
if(l1>l2)
{
max=l1;
c=l1-l2;
for(j=1;j<=c;j++)
s2=”0″+s2;
}
if(l2>l1)
{
max=l2;
c=l2-l1;
for(j=1;j<=c;j++)
s1=”0″+s1;
}
for(int i=max-1;i>=0;i–)
{
char ch1=s1.charAt(i);
char ch2=s2.charAt(i);
sum=Integer.parseInt(Character.toString(ch1))+Integer.parseInt(Character.toString(ch2))+cr;
if(sum==0)
{ sm=0; cr=0; }
if(sum==1)
{ sm=1; cr=0; }
if(sum==2)
{ sm=0; cr=1; }
if(sum==3)
{
sm=1; cr=1; }
String temp=Integer.toString(sm);
add=temp+add;
}
System.out.println(“Sum = “+add);
}
}