![]() |
VOOZH | about |
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).
The idea is to use bitwise operators. Addition of two numbers has been discussed using Bitwise operators. Like addition, the idea is to use subtractor logic.
The truth table for the half subtractor is given below.
X Y Diff Borrow 0 0 0 0 0 1 1 1 1 0 1 0 1 1 0 0
From the above table one can draw the Karnaugh map for "difference" and "borrow".
So, Logic equations are:
Diff = y ? x Borrow = x' . y
Source: Wikipedia page for subtractor
Following is implementation based on above equations.
Output :
x - y is 16
Time Complexity: O(log y)
Auxiliary Space: O(1)
Following is recursive implementation for the same approach.
Output :
x - y is 16
Time Complexity: O(log y)
Auxiliary Space: O(log y)
This article is contributed Dheeraj.