![]() |
VOOZH | about |
Given a binary numbers 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:
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 = 1001Input: "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:
0110 10111
Time Complexity: O(n), as each bit is processed once.
Space Complexity: O(1), as no extra space is used.