Advertisement
win98se

Peh Zhengyan the Great Wizard's Programming Challenge (0)

Sep 16th, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class BinaryAddition
  4. {
  5.     public static void main(String[] args)
  6.     {
  7.         Scanner i=new Scanner(System.in);
  8.         System.out.print("Enter first number: ");
  9.         int n1=Integer.parseInt(i.nextLine());
  10.         System.out.print("Enter second number: ");
  11.         int n2=Integer.parseInt(i.nextLine());
  12.         String sum=magic(n1, n2);
  13.         System.out.println("Sum in binary = "+sum);
  14.     }
  15.    
  16.     public static String magic(int n1, int n2)
  17.     {
  18.         int sum=n1+n2, i=1, temp=sum;
  19.         String str="";
  20.         do
  21.         {
  22.             i*=2;
  23.         } while(sum>i);
  24.         while(i>1)
  25.         {
  26.             i/=2;
  27.             if(temp-i>=0)
  28.             {
  29.                 temp-=i;
  30.                 str+="1";
  31.             }
  32.             else
  33.                 str+="0";
  34.         }
  35.         return(str);
  36.     }
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement