Find Two's Complement
00:00
Given a binary string s representing an unsigned binary number, find and return its two's complement representation as a binary string of the same length.
In fixed-width binary arithmetic, the two's complement of a binary number is obtained by inverting all of its bits (changing 0s to 1s and 1s to 0s) to get the one's complement, and then adding 1 to the least significant bit (LSB). Any carry-out bit beyond the original length of the string should be discarded.
Constraints
1 <= s.length <= 10^5sconsists only of characters'0'and'1'
Examples
Input → "101010"
Output → "010110"
Explanation:
The 1's complement of '101010' is '010101'. Adding 1 yields '010110'.
Input → "0000"
Output → "0000"
Explanation:
The 1's complement of '0000' is '1111'. Adding 1 yields '10000'. Discarding the overflow bit gives '0000'.
Input → "1"
Output → "1"
Explanation:
The 1's complement of '1' is '0'. Adding 1 yields '1'.