Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class BinaryAddition
- {
- public static void main(String[] args)
- {
- Scanner i=new Scanner(System.in);
- System.out.print("Enter first number: ");
- int n1=Integer.parseInt(i.nextLine());
- System.out.print("Enter second number: ");
- int n2=Integer.parseInt(i.nextLine());
- String sum=magic(n1, n2);
- System.out.println("Sum in binary = "+sum);
- }
- public static String magic(int n1, int n2)
- {
- int sum=n1+n2, i=1, temp=sum;
- String str="";
- do
- {
- i*=2;
- } while(sum>i);
- while(i>1)
- {
- i/=2;
- if(temp-i>=0)
- {
- temp-=i;
- str+="1";
- }
- else
- str+="0";
- }
- return(str);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement