Posts

Showing posts from July 3, 2014

Half Adder in Java(for same length)

import java.io.*;
import java.lang.*;
public class adder
{
public static void main(String args[])throws Exception
{
DataInputStream dd= new DataInputStream(System.in);
System.out.println("Enter two Numbers");
String a=dd.readLine();
String b=dd.readLine();
int i=0,sum=0,carry=0,total=0;


String s="";

//assuming they are of equal length

for(i=b.length()-1;i>=0;i--)
{
char a1=a.charAt(i);
char a2=b.charAt(i);
total+=(int)a1+(int)a2-96;
switch(total)
{
case 0: sum=0;carry=0;break;
case 1: sum=1;carry=0;break;
case 2: sum=0;carry=1;break;
case 3: sum=1;carry=1;break;
}
s=sum+s;
total=carry;


}
if(carry!=0)
s=carry+s;
System.out.println("sum is:"+s);
}
}