Given a Binary Number as string, print its 2’s complements.
2’s complement of a binary number is 1 added to the 1’s complement of the binary number. Note that 1’s complement is simply flip of given binary number.
2's complement of "0111" is "1001" 2's complement of "1100" is "0100"
We strongly recommend that you click here and practice it, before moving on to the solution.
We have discussed 1’s and 2’s complements in below post.
The method discussed in above post traverses binary string twice to find 2’s complement, first finds 1’s complement, then finds 2’s complement using 1’s complement
In this post an efficient method for 2’s complement is discussed that traverses string only once. We traverse the string from last till the single 1 is not traversed and after that flip all values of string i.e. 0 to 1 and 1 to 0.
Note: Here to handle the corner case i.e. if 1 doesn’t exist in the string then just append 1 in the starting of string.
Input: str = "1000100" Output: 0111100 Explanation: Starts traversing the string from last, we got first '1' at index 4 then just flip the bits of 0 to 3 indexes to make the 2's complement. Input: str = "0000" Output: 10000 Explanation: As there is no 1 in the string so just append '1' at starting.
This article is contributed by Sahil Chhabra (akku). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- 1's and 2's complement of a Binary Number
- Check if binary representation of a given number and its complement are anagram
- What’s difference between 1's Complement and 2's Complement?
- Write an Efficient Method to Check if a Number is Multiple of 3
- Longest sub string of 0's in a binary string which is repeated K times
- Python | Check if a given string is binary string or not
- Largest sub-string of a binary string divisible by 2
- 9's complement of a decimal number
- Find One's Complement of an Integer
- Complement of a number with any base b
- 10's Complement of a decimal number
- Previous number same as 1's complement
- Subtraction of two numbers using 2's Complement
- Check if one of the numbers is one's complement of the other
- Why are negative numbers stored as 2's complement?