### Sum of two Binary numbers

**import java.util.*;**

class BinarySum

{

public int n,m,p,q,r;

public void input()

{

// two binary numbers added by converting into decimal

// and sum then converted into binary

Scanner br = new Scanner(System.in);

System.out.println(" Input a binary number n");

n=br.nextInt();

System.out.println(" Input a binary number m");

m=br.nextInt();

}

public void calculate()

{

p=bintodec(n);

q=bintodec(m);

if(p== -1 || q== -1)

System.out.println("INVALID BINARY VALUE ");

else

{

System.out.println("Binary number " + n + " in decimal is " + p);

System.out.println("Binary number " + m + " in decimal is " + q);

r=sumbin(p+q);

System.out.println("Sum of two binary number " + n + " and " + m + " is " + r);

}

}

public int bintodec(int x)

{

int a,s=0, i=0;

while(x>0)

{

a=x%10;

if(a>1) return -1;

s = s + (int)Math.pow(2,i)*a;

x=x/10;

i++;

}

return s;

}

public int sumbin(int x)

{

int a,s=0, i=0;

while(x>0)

{

a=x%2;

s = s + (int)Math.pow(10,i)*a;

x=x/2;

i++;

}

return s;

}

public static void main(String arg[])

{

BinarySum ob= new BinarySum();

ob.input();

ob.calculate();

}

}

class BinarySum

{

public int n,m,p,q,r;

public void input()

{

// two binary numbers added by converting into decimal

// and sum then converted into binary

Scanner br = new Scanner(System.in);

System.out.println(" Input a binary number n");

n=br.nextInt();

System.out.println(" Input a binary number m");

m=br.nextInt();

}

public void calculate()

{

p=bintodec(n);

q=bintodec(m);

if(p== -1 || q== -1)

System.out.println("INVALID BINARY VALUE ");

else

{

System.out.println("Binary number " + n + " in decimal is " + p);

System.out.println("Binary number " + m + " in decimal is " + q);

r=sumbin(p+q);

System.out.println("Sum of two binary number " + n + " and " + m + " is " + r);

}

}

public int bintodec(int x)

{

int a,s=0, i=0;

while(x>0)

{

a=x%10;

if(a>1) return -1;

s = s + (int)Math.pow(2,i)*a;

x=x/10;

i++;

}

return s;

}

public int sumbin(int x)

{

int a,s=0, i=0;

while(x>0)

{

a=x%2;

s = s + (int)Math.pow(10,i)*a;

x=x/2;

i++;

}

return s;

}

public static void main(String arg[])

{

BinarySum ob= new BinarySum();

ob.input();

ob.calculate();

}

}

## 1 comment:

sir ur website is a great help

sir thanks a lot ---ali

Post a Comment