Subtract two numbers without using arithmetic operators

Posted on Updated on

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.

Output:

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.