Open In App

1's and 2's complement of a Binary Number

Last Updated : 20 Mar, 2025
Comments
Improve
Suggest changes
44 Likes
Like
Report

Given a binary number s represented as a string. The task is to return its 1's complement and 2's complement in form of an array as [onesComplement, twosComplement].

The 1's complement of a binary number is obtained by flipping all its bits. 0 becomes 1, and 1 becomes 0. Positive numbers remain unchanged whereas negative numbers are represented by taking the 1's complement of their positive counterparts.

For example, in 8-bit notation:

  • +9 is represented as 00001001.
  • -9 is represented as 11110110, which is the 1's complement of 00001001.

Examples: 

Input: s = "0111"
Output: 1000
Explanation: Each bit is flipped, i.e. 0 becomes 1, and 1 becomes 0.

Input: s= "1100"
Output: 0011
Explanation: Each bit is flipped, i.e. 0 becomes 1, and 1 becomes 0.

The 2's complement of a binary number is obtained by finding the 1's complement (flipping all bits) and then adding 1 to the result. In 2's complement representation, the Most Significant Bit (MSB) represents the sign. A 0 indicates a positive number, while a 1 indicates a negative number. The remaining bits represent the magnitude.

Positive numbers are represented the same way as in 1's complement and sign-bit representation. Negative numbers are obtained by taking the 2's complement of their positive counterparts.

Examples:

Input: s = "0111"
Output: 1001
Explanation: Find 1's complement -> 1000, then add 1 -> 1000 + 1 = 1001

Input: "1100"
Output: 0100
Explanation: Find 1's complement -> 0011, then add 1 -> 0011 + 1 = 0100

The idea is to first compute the 1's complement by flipping each bit of the binary string. Then, to find the 2's complement, we add 1 to the 1's complement, starting from the rightmost bit. If all bits are flipped, an extra '1' is added at the beginning. This ensures correct representation in signed binary numbers.

Steps to implement the above idea:

  • onesComplement() iterates through s and flip each '0' to '1' and '1' to '0'.
  • twosComplement() calls onesComplement, then add 1 to the least significant bit.
  • Traverse s from right to left, flipping '1' to '0' until the first '0', which is changed to '1'.
  • If no '0' is found, prepend '1' to s to maintain the correct two’s complement representation.
C++
Java Python C# JavaScript

Output
0110 10111

Time Complexity: O(n), as each bit is processed once.
Space Complexity: O(1), as no extra space is used.


Next Article

Similar Reads