# Subtract two numbers without using arithmetic operators

Problem Statement:

Subtract two numbers without using arithmetic operators

Write a function subtract(x, y) that returns x-y where x and y are integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc).

**We suggest you think about a solution before reading further…**

Solution:

Find borrow by doing AND (&) of complement of x and y. Now borrow contains common set bits of y and unset bits of x. Subtraction can be obtained from taking an AND of x and y after getting the borrow. Left shift borrow by 1, so subtracting it from x gives required sum. The same logic can be implemented iteratively as well as recursively as shown below.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
//Subtract two numbers without using arithmetic operators public class SubtractTwoNumbers { public static void main(String[] args) { int a = 30; int b = 10; int ans1 = subIterative(a, b); System.out.println("By Iterative method : "+ ans1); int ans2 = subRecursion(a,b); System.out.println("By Recursive method : "+ ans2); } private static int subIterative(int a, int b) { //iterate till second no becomes 0 while(b != 0){ // borrow contains common set bits of b and unset bits of a int borrow = (~a) & b; // Subtraction of bits of 'a' and 'b' where at least one of the bits is not set a = a ^ b; // Borrow is shifted by one so that subtracting it from 'a' gives the required sum b = borrow << 1; } return a; } private static int subRecursion(int a, int b) { if(b == 0){ return a; }else{ //Pass Sum, Carry shifted by 1 recursively return subRecursion(a ^ b, (~a & b) << 1); } } } |

Output:

1 2 |
By Iterative method : 20 By Recursive method : 20 |