VOOZH about

URL: https://www.geeksforgeeks.org/dsa/subtraction-of-two-numbers-using-2s-complement/

⇱ Subtraction of two numbers using 2's Complement - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Subtraction of two numbers using 2's Complement

Last Updated : 13 Mar, 2023

Given two numbers a and b. The task is to subtract b from a by using 2's Complement method.
Note: Negative numbers represented as 2's Complement of Positive Numbers.
For example, -5 can be represented in binary form as 2's Complement of 5. Look at the image below: 

👁 Image

Examples

Input : a = 2, b = 3
Output : -1

Input : a = 9, b = 7
Output : 2 

To subtract b from a. Write the expression (a-b) as:  

(a - b) = a + (-b)

Now (-b) can be written as (2's complement of b). So the above expression can be now written as:  

(a - b) = a + (2's complement of b)

So, the problem now reduces to "Add a to the 2's complement of b". The below image illustrates the above method of subtraction for the first example where a = 2 and b = 3. 

👁 Image


Below is the implementation of the above method: 


Output
-1
2

Time complexity - O(nlog2(n))
Auxiliary Space - O(1)

Method 2: Basic Approach or Brute Force Approach

Subtraction of two Binary Numbers, subtract two binary numbers using 2's Complement method. 

Step-1: Find the 2's complement of the subtrahend. 

Step-2: Add the first number and 2's complement of the subtrahend. 

Step-3: If the carry is produced, discard the carry. If there is no carry then take the 2's complement of the result. 

Below is the implementation of the above approach.


Output
-00101

Time complexity : O(N)

Auxiliary Space : O(1)


 

Comment