sandeshMC

BINARY ADDITION COA

Apr 13th, 2014
45
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.42 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class BinaryAddition {
  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.         if (flag == 1)
  32.             result[0] = 1;
  33.  
  34.         return result;
  35.  
  36.     }
  37.  
  38.     public static void main(String[] args) {
  39.         // TODO Auto-generated method stub
  40.         Scanner sc = new Scanner(System.in);
  41.         System.out.println("Enter the first number : ");
  42.         int x = sc.nextInt();
  43.         System.out.println("Enter the second number : ");
  44.         int y = sc.nextInt();
  45.         int greater = x > y ? x : y;
  46.         int length = (int) (Math.log(Math.abs(greater)) / Math.log(2)) + 2;
  47.         int a[] = decimalToBinary(x, length);
  48.         int b[] = decimalToBinary(y, length);
  49.         System.out.println("a : " + Arrays.toString(a) + "  \nb : "
  50.                 + Arrays.toString(b));
  51.         System.out.println("RESULT : " + Arrays.toString(add(a, b)));
  52.     }
  53.  
  54. }
  55. /*
  56.  Enter the first number :
  57. 34
  58. Enter the second number :
  59. 30
  60. a : [0, 1, 0, 0, 0, 1, 0]  
  61. b : [0, 0, 1, 1, 1, 1, 0]
  62. RESULT : [1, 0, 0, 0, 0, 0, 0]
  63.  
  64.  */
Advertisement
Add Comment
Please, Sign In to add comment