sandeshMC

BINARY SUBTRACTION COA

Apr 13th, 2014
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class BinarySubtraction {
  4.     static int flag = 0;
  5.  
  6.     /**
  7.      * @param args
  8.      */
  9.     static int[] decimalToBinary(int a, int length) {
  10.  
  11.         int binary[] = new int[length];
  12.         int i = binary.length - 1;
  13.         if (a < 0) {
  14.             a = (int) (Math.pow(2, length)) - Math.abs(a);
  15.         }
  16.         while (a != 0) {
  17.             binary[i] = a % 2;
  18.             a /= 2;
  19.             i--;
  20.         }
  21.  
  22.         return binary;
  23.     }
  24.  
  25.     static int[] add(int a[], int b[]) {
  26.         int[] result = new int[a.length];
  27.         for (int i = a.length - 1; i >= 0; i--) {
  28.             result[i] = (a[i] + b[i] + flag) % 2;
  29.             flag = (a[i] + b[i] + flag) / 2;
  30.         }
  31.  
  32.         return result;
  33.  
  34.     }
  35.  
  36.     public static void main(String[] args) {
  37.         // TODO Auto-generated method stub
  38.         Scanner sc = new Scanner(System.in);
  39.         System.out.println("Enter the first number : ");
  40.         int x = sc.nextInt();
  41.         System.out.println("Enter the second number : ");
  42.         int y = sc.nextInt();
  43.         int greater = Math.abs(x) > Math.abs(y) ? Math.abs(x) : Math.abs(y);
  44.         int length = (int) (Math.log(Math.abs(greater)) / Math.log(2)) + 2;
  45.         int a[] = decimalToBinary(x, length);
  46.         int b[] = decimalToBinary(y, length);
  47.         System.out.println("a : " + Arrays.toString(a) + "  \nb : "
  48.                 + Arrays.toString(b));
  49.         System.out.println("RESULT : " + Arrays.toString(add(a, b)));
  50.     }
  51.  
  52. }
  53. /*
  54.  * Enter the first number : 5 Enter the second number : -9
  55.  * a : [0, 0, 1, 0, 1]
  56.  * b : [1, 0, 1, 1, 1]
  57.  * RESULT : [1, 1, 1, 0, 0]
  58.  */
Advertisement
Add Comment
Please, Sign In to add comment