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

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

Last Updated : 15 Dec, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Number as a string, print its 1’s and 2’s complements.
 

1’s complement of a binary number is another binary number obtained by toggling all bits in it, i.e., transforming the 0 bit to 1 and the 1 bit to 0.In the 1’s complement format , the positive numbers remain unchanged . The negative numbers are obtained by taking the 1’s complement of positive counterparts.

for example +9 will be represented as 00001001 in eight-bit notation and -9 will be represented as 11110110, which is the 1’s complement of 00001001.

Examples: 

1's complement of "0111" is "1000"
1's complement of "1100" is  "0011" 

2’s complement of a binary number is 1, added to the 1’s complement of the binary number. In the 2’s complement representation of binary numbers, the MSB represents the sign with a ‘0’ used for plus sign and a  ‘1’ used for a minus sign. the remaining bits are used for representing magnitude. positive magnitudes are represented in the same way as in the case of sign-bit or 1’s complement representation.  Negative magnitudes are represented by the 2’s complement of their positive counterparts.

Examples: 

2's complement of "0111" is  "1001"
2's complement of "1100" is  "0100" 

Another trick to finding two’s complement:

Step 1:  Start from the Least Significant Bit and traverse left until you find a 1.  Until you find 1, the bits stay the same

Step 2: Once you have found 1, let the 1 as it is, and now

Step 3: Flip all the bits left into the 1.

Illustration

Suppose we need to find 2s Complement of 100100

Step 1: Traverse and let the bit stay the same until you find 1. Here x is not known yet. Answer = xxxx00 –

Step 2: You found 1. Let it stay the same. Answer = xxx100

Step 3: Flip all the bits left into the 1. Answer = 011100.

Hence, the 2s complement of 100100 is 011100.

Recommended Practice

For one’s complement, we simply need to flip all bits. 
For 2’s complement, we first find one’s complement. We traverse the one’s complement starting from LSB (least significant bit), and look for 0. We flip all 1’s (change to 0) until we find a 0. Finally, we flip the found 0. For example, 2’s complement of “01000” is “11000” (Note that we first find one’s complement of 01000 as 10111).   If there are all 1’s (in one’s complement), we add an extra 1 in the string. For example, 2’s complement of “000” is “1000” (1’s complement of “000” is “111”).

Below is the implementation. 

C++




// C++ program to print 1's and 2's complement of
// a binary number
#include <bits/stdc++.h>
using namespace std;
  
// Returns '0' for '1' and '1' for '0'
char flip(char c) {return (c == '0')? '1': '0';}
  
// Print 1's and 2's complement of binary number
// represented by "bin"
void printOneAndTwosComplement(string bin)
{
    int n = bin.length();
    int i;
  
    string ones, twos;
    ones = twos = "";
  
    //  for ones complement flip every bit
    for (i = 0; i < n; i++)
        ones += flip(bin[i]);
  
    //  for two's complement go from right to left in
    //  ones complement and if we get 1 make, we make
    //  them 0 and keep going left when we get first
    //  0, make that 1 and go out of loop
    twos = ones;
    for (i = n - 1; i >= 0; i--)
    {
        if (ones[i] == '1')
            twos[i] = '0';
        else
        {
            twos[i] = '1';
            break;
        }
    }
  
    // If No break : all are 1  as in 111  or  11111;
    // in such case, add extra 1 at beginning
    if (i == -1)
        twos = '1' + twos;
  
  
    cout << "1's complement: " << ones << endl;
    cout << "2's complement: " << twos << endl;
}
  
// Driver program
int main()
{
    string bin = "1100";
    printOneAndTwosComplement(bin);
    return 0;
}


Java




// Java program to print 1's and 2's complement of
// a binary number
  
class GFG 
{
  
    // Returns '0' for '1' and '1' for '0'
    static char flip(char c)
    {
        return (c == '0') ? '1' : '0';
    }
  
    // Print 1's and 2's complement of binary number
    // represented by "bin"
    static void printOneAndTwosComplement(String bin)
    {
        int n = bin.length();
        int i;
  
        String ones = "", twos = "";
        ones = twos = "";
  
        // for ones complement flip every bit
        for (i = 0; i < n; i++)
        {
            ones += flip(bin.charAt(i));
        }
  
        // for two's complement go from right to left in
        // ones complement and if we get 1 make, we make
        // them 0 and keep going left when we get first
        // 0, make that 1 and go out of loop
        twos = ones;
        for (i = n - 1; i >= 0; i--)
        {
            if (ones.charAt(i) == '1')
            {
                twos = twos.substring(0, i) + '0' + twos.substring(i + 1);
            
            else
            {
                twos = twos.substring(0, i) + '1' + twos.substring(i + 1);
                break;
            }
        }
  
        // If No break : all are 1 as in 111 or 11111;
        // in such case, add extra 1 at beginning
        if (i == -1)
        {
            twos = '1' + twos;
        }
  
        System.out.println("1's complement: " + ones);;
        System.out.println("2's complement: " + twos);
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String bin = "1100";
        printOneAndTwosComplement(bin);
    }
}
  
// This code contributed by Rajput-Ji


Python3




# Python3 program to print 1's and 2's 
# complement of a binary number 
  
# Returns '0' for '1' and '1' for '0' 
def flip(c):
    return '1' if (c == '0') else '0'
  
# Print 1's and 2's complement of 
# binary number represented by "bin" 
def printOneAndTwosComplement(bin):
  
    n = len(bin
    ones = ""
    twos = ""
      
    # for ones complement flip every bit 
    for i in range(n):
        ones += flip(bin[i]) 
  
    # for two's complement go from right 
    # to left in ones complement and if
    # we get 1 make, we make them 0 and 
    # keep going left when we get first 
    # 0, make that 1 and go out of loop 
    ones = list(ones.strip(""))
    twos = list(ones)
    for i in range(n - 1, -1, -1):
      
        if (ones[i] == '1'):
            twos[i] = '0'
        else:         
            twos[i] = '1'
            break
  
    i -= 1    
    # If No break : all are 1 as in 111 or 11111 
    # in such case, add extra 1 at beginning 
    if (i == -1):
        twos.insert(0, '1'
  
    print("1's complement: ", *ones, sep = "")
    print("2's complement: ", *twos, sep = "")
      
# Driver Code
if __name__ == '__main__':
    bin = "1100"
    printOneAndTwosComplement(bin.strip(""))
      
# This code is contributed 
# by SHUBHAMSINGH10


C#




// C# program to print 1's and 2's complement of
// a binary number
using System;
  
class GFG 
{
  
    // Returns '0' for '1' and '1' for '0'
    static char flip(char c)
    {
        return (c == '0') ? '1' : '0';
    }
  
    // Print 1's and 2's complement of binary number
    // represented by "bin"
    static void printOneAndTwosComplement(String bin)
    {
        int n = bin.Length;
        int i;
  
        String ones = "", twos = "";
        ones = twos = "";
  
        // for ones complement flip every bit
        for (i = 0; i < n; i++)
        {
            ones += flip(bin[i]);
        }
  
        // for two's complement go from right to left in
        // ones complement and if we get 1 make, we make
        // them 0 and keep going left when we get first
        // 0, make that 1 and go out of loop
        twos = ones;
        for (i = n - 1; i >= 0; i--)
        {
            if (ones[i] == '1')
            {
                twos = twos.Substring(0, i) + '0'
                twos.Substring(i + 1,twos.Length-(i+1));
            
            else
            {
                twos = twos.Substring(0, i) + '1'
                twos.Substring(i + 1,twos.Length-(i+1));
                break;
            }
        }
  
        // If No break : all are 1 as in 111 or 11111;
        // in such case, add extra 1 at beginning
        if (i == -1)
        {
            twos = '1' + twos;
        }
  
        Console.WriteLine("1's complement: " + ones);;
        Console.WriteLine("2's complement: " + twos);
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        String bin = "1100";
        printOneAndTwosComplement(bin);
    }
}
  
// This code has been contributed by 29AjayKumar


Javascript




<script>
  
// Javascript program to print 1's and 2's complement of
// a binary number
  
// Returns '0' for '1' and '1' for '0'
function flip (c) {return (c == '0')? '1': '0';}
  
// Print 1's and 2's complement of binary number
// represented by "bin"
function printOneAndTwosComplement(bin)
{
    var n = bin.length;
    var i;
  
    var ones, twos;
    ones = twos = "";
  
    //  for ones complement flip every bit
    for (i = 0; i < n; i++)
        ones += flip(bin[i]);
  
    //  for two's complement go from right to left in
    //  ones complement and if we get 1 make, we make
    //  them 0 and keep going left when we get first
    //  0, make that 1 and go out of loop
    twos = ones;
    twos = twos.split('')
    for (i = n - 1; i >= 0; i--)
    {
        if (ones[i] == '1')
            twos[i] = '0';
        else
        {
            twos[i] = '1';
            break;
        }
    }
    twos = twos.join('')
    // If No break : all are 1  as in 111  or  11111;
    // in such case, add extra 1 at beginning
    if (i == -1)
        twos = '1' + twos;
  
  
    document.write( "1's complement: " + ones + "<br>");
    document.write( "2's complement: " + twos + "<br>");
}
  
// Driver program
var bin = "1100";
printOneAndTwosComplement(bin);
  
</script>


Output: 

1's complement: 0011
2's complement: 0100

Time Complexity: O(n)

Auxiliary Space: O(1)

Thanks to Utkarsh Trivedi for the above solution.
As a side note, signed numbers generally use 2’s complement representation. Positive values are stored as it is and negative values are stored in their 2’s complement form. One extra bit is required to indicate whether the number is positive or negative. For example, char is 8 bits in C. If 2’s complement representation is used for char, then 127 is stored as it is, i.e., 01111111, where first 0 indicates positive. But -127 is stored as 10000001.
Related Post : 
Efficient method for 2’s complement of a binary string

References: 
http://qa.geeksforgeeks.org/6439/write-program-calculate-ones-and-twos-complement-of-number 
https://www.geeksforgeeks.org/difference-between-1s-complement-representation-and-2s-complement-representation-technique/
 



Previous Article
Next Article

Similar Reads

Difference between 1's Complement representation and 2's Complement representation Technique
Prerequisite - Representation of Negative Binary Numbers 1's complement of a binary number is another binary number obtained by toggling all bits in it, i.e., transforming the 0 bit to 1 and the 1 bit to 0. Examples: Let numbers be stored using 4 bits 1's complement of 7 (0111) is 8 (1000) 1's complement of 12 (1100) is 3 (0011) 2's complement of a
3 min read
Check if binary representation of a given number and its complement are anagram
Given a positive number you need to check whether it's complement and the number are anagrams or not.Examples: Input : a = 4294967295 Output : Yes Binary representation of 'a' and it's complement are anagrams of each other Input : a = 4 Output : No Simple Approach: In this approach calculation of the complement of the number is allowed.1. Find bina
9 min read
Efficient method for 2's complement of a binary string
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. Examples: 2's complement of "0111" is "1001" 2's complement of "1100" is "0100" We strongly recommend that you click here and practice it,
6 min read
8085 program to find 1's and 2's complement of 8-bit number
Problem - Write a program to find 1's and 2's complement of 8-bit number where starting address is 2000 and the number is stored at 3000 memory address and store result into 3001 and 3002 memory address. Example - Algorithm - Load the data from memory 3000 into A (accumulator)Complement content of accumulatorStore content of accumulator in memory 3
2 min read
8085 program to find 1’s and 2’s complement of 16-bit number
Prerequisite - 8085 program to find 1’s and 2’s complement of 8-bit number Problem - – Write a program to find 1’s and 2’s complement of 16-bit number where starting address is 2000 and the number is stored at 3000 memory address and store result into 3002 and 3004 memory address. Example - Algorithm - Load a 16-bit number from memory 3000 into a r
2 min read
Interface 8255 with 8085 microprocessor for 1’s and 2’s complement of a number
Introduction : The 8255 is a programmable peripheral interface chip that can be interfaced with the 8085 microprocessor to perform various input/output operations. One of the operations that can be performed using the 8255 and the 8085 microprocessor is finding the 1's and 2's complement of a number. The 1's complement of a binary number is obtaine
4 min read
Previous number same as 1's complement
Given a number check whether binary representation of its predecessor and its 1's complement are same or not. Examples: Input : 14 Output : NO Storing 14 as a 4 bit number, 14 (1110), its predecessor 13 (1101), its 1's complement 1 (0001), 13 and 1 are not same in their binary representation and hence output is NO.Input : 8 Output : YES Storing 8 a
4 min read
10's Complement of a decimal number
Given a decimal number N. The task is to find 10’s complement of the number N.Example: Input : 25 Output : 10's complement is : 75 Input : 456 Output : 10's complement is : 544 10’s complement of a decimal number can be found by adding 1 to the 9's complement of that decimal number. It is just like 2s complement in binary number representation.Math
4 min read
Complement of a number with any base b
In this post, a general method of finding complement with any arbitrary base [Tex]b [/Tex]is discussed. Remember: It is recommended to go through below as follows: One’s Complement of an Integer1’s and 2’s complement of a Binary Number Steps to find (b-1)’s complement: To find (b-1)’s complement, Subtract each digit of the number from the largest n
6 min read
9's complement of a decimal number
9's complement of a decimal number is the subtraction of it's each digits from 9. Like 1's complement, 9's complement is used to subtract a number using addition.For example, let us compute value of "718 - 123" using 9's complement and addition. We first find 9's complement of 718 which is 281. Now we add 281 to 123. We get 404. 9's complement of t
4 min read