Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class BinarySubtraction {
- static int flag = 0;
- /**
- * @param args
- */
- static int[] decimalToBinary(int a, int length) {
- int binary[] = new int[length];
- int i = binary.length - 1;
- if (a < 0) {
- a = (int) (Math.pow(2, length)) - Math.abs(a);
- }
- while (a != 0) {
- binary[i] = a % 2;
- a /= 2;
- i--;
- }
- return binary;
- }
- static int[] add(int a[], int b[]) {
- int[] result = new int[a.length];
- for (int i = a.length - 1; i >= 0; i--) {
- result[i] = (a[i] + b[i] + flag) % 2;
- flag = (a[i] + b[i] + flag) / 2;
- }
- return result;
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- Scanner sc = new Scanner(System.in);
- System.out.println("Enter the first number : ");
- int x = sc.nextInt();
- System.out.println("Enter the second number : ");
- int y = sc.nextInt();
- int greater = Math.abs(x) > Math.abs(y) ? Math.abs(x) : Math.abs(y);
- int length = (int) (Math.log(Math.abs(greater)) / Math.log(2)) + 2;
- int a[] = decimalToBinary(x, length);
- int b[] = decimalToBinary(y, length);
- System.out.println("a : " + Arrays.toString(a) + " \nb : "
- + Arrays.toString(b));
- System.out.println("RESULT : " + Arrays.toString(add(a, b)));
- }
- }
- /*
- * Enter the first number : 5 Enter the second number : -9
- * a : [0, 0, 1, 0, 1]
- * b : [1, 0, 1, 1, 1]
- * RESULT : [1, 1, 1, 0, 0]
- */
Advertisement
Add Comment
Please, Sign In to add comment