Java Program to Find Subtraction of Two Numbers Using Binary Subtraction

You are currently viewing Java Program to Find Subtraction of Two Numbers Using Binary Subtraction

Java program to find subtraction of two numbers using binary subtraction

// Java program to find subtraction of two numbers 
// using binary subtraction

import java.util.Scanner;

public class Main {

  static int binAddition(int a, int b) {
    int c; //carry

    while (b != 0) {
      //find carry and shift it left

      c = (a & b) << 1;

      //find the sum
      a = a ^ b;
      b = c;
    }
    return a;
  }

  static int binSubtracton(int a, int b) {
    int carry;

    //get 2's compliment of b and add in a
    b = binAddition(~b, 1);

    while (b != 0) {
      //find carry and shift it left
      carry = (a & b) << 1;

      a = a ^ b;
      b = carry;
    }
    return a;
  }

  public static void main(String[] args) {
    Scanner SN = new Scanner(System.in);

    int num1 = 0;
    int num2 = 0;
    int add = 0;

    System.out.printf("Input first integer value: ");
    num1 = SN.nextInt();

    System.out.printf("Input second integer value: ");
    num2 = SN.nextInt();

    add = binSubtracton(num1, num2);
    System.out.printf("Binary Subtraction is: %d\n", add);
  }
}

Output

Input first integer value: 34
Input second integer value: 23
Binary Subtraction is: 11

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply