Find 2's Complement of a Binary String

Last Updated : 25 Jul, 2026

Given a binary string s, find its 2's complement and return the result as a binary string of the same length.
The 2's complement of a binary number is obtained by first flipping all its bits (0 to 1 and 1 to 0) and then adding 1 to the resulting binary number.

Note: 2's complement of 0 is always 0. 

Examples: 

Input: s = "00000101"
Output: 11111011
Explanation: Flip all the bits to get 11111010, then add 1 to obtain 11111011.

Input: s = "0000"
Output: 0000
Explanation: Flipping all bits gives 1111. Adding 1 causes a carry to ripple through every position (1+1=10 at each bit, carrying left each time), which would normally produce a 5-bit result of 10000. But since numbers are stored in a fixed number of bits (just like a hardware register of fixed width), the overflowing carry bit simply falls off and is discarded, leaving 0000. This matches the fact that in two's complement, there is only one representation of zero - there's no separate "negative zero".

Try It Yourself
redirect icon

[Naive Approach] Flip All Bits and Simulate Binary Addition - O(n) Time and O(1) Space

The idea is to first compute the 1's complement by flipping every bit of the binary string. Then, simulate the addition of 1 from the least significant bit while propagating the carry until it becomes 0 or all bits are processed.

Working of Approach:

  • Flip every bit of the binary string to obtain its 1's complement.
  • Start adding 1 from the rightmost bit.
  • If the current bit is 0, change it to 1 and stop; otherwise, make it 0 and carry 1 to the next bit.
  • The resulting string is the required 2's complement.
C++
#include <bits/stdc++.h>
using namespace std;

string twosComplement(string s)
{

    // Flip all bits
    for (int i = 0; i < s.size(); i++)
    {
        s[i] = (s[i] == '0') ? '1' : '0';
    }

    // Add 1 to the flipped string
    int carry = 1;

    for (int i = s.size() - 1; i >= 0; i--)
    {

        if (carry == 0)
            break;

        if (s[i] == '0')
        {
            s[i] = '1';
            carry = 0;
        }
        else
        {
            s[i] = '0';
            carry = 1;
        }
    }

    return s;
}

int main()
{

    string s = "00000101";
    cout << twosComplement(s);
    return 0;
}
Java
public class GFG {

    public static String twosComplement(String s)
    {

        // Flip all bits
        for (int i = 0; i < s.length(); i++) {
            s = s.substring(0, i)
                + (s.charAt(i) == '0' ? '1' : '0')
                + s.substring(i + 1);
        }

        // Add 1 to the flipped string
        int carry = 1;

        for (int i = s.length() - 1; i >= 0; i--) {

            if (carry == 0)
                break;

            if (s.charAt(i) == '0') {
                s = s.substring(0, i) + '1'
                    + s.substring(i + 1);
                carry = 0;
            }
            else {
                s = s.substring(0, i) + '0'
                    + s.substring(i + 1);
                carry = 1;
            }
        }

        return s;
    }

    public static void main(String[] args)
    {
        String s = "00000101";
        System.out.println(twosComplement(s));
    }
}
Python
def twosComplement(s):

    # Flip all bits
    s = ''.join(['1' if bit == '0' else '0' for bit in s])

    # Add 1 to the flipped string
    carry = 1
    s_list = list(s)

    for i in range(len(s_list) - 1, -1, -1):
        if carry == 0:
            break
        if s_list[i] == '0':
            s_list[i] = '1'
            carry = 0
        else:
            s_list[i] = '0'
            carry = 1

    return ''.join(s_list)


if __name__ == "__main__":
    s = "00000101"
    print(twosComplement(s))
C#
using System;

public class GFG {
    public static string twosComplement(string s)
    {

        // Flip all bits
        for (int i = 0; i < s.Length; i++) {
            s = s.Substring(0, i)
                + (s[i] == '0' ? '1' : '0')
                + s.Substring(i + 1);
        }

        // Add 1 to the flipped string
        int carry = 1;

        for (int i = s.Length - 1; i >= 0; i--) {
            if (carry == 0)
                break;

            if (s[i] == '0') {
                s = s.Substring(0, i) + '1'
                    + s.Substring(i + 1);
                carry = 0;
            }
            else {
                s = s.Substring(0, i) + '0'
                    + s.Substring(i + 1);
                carry = 1;
            }
        }

        return s;
    }

    public static void Main()
    {
        string s = "00000101";
        Console.WriteLine(twosComplement(s));
    }
}
JavaScript
function twosComplement(s)
{

    // Flip all bits
    for (let i = 0; i < s.length; i++) {
        s = s.substring(0, i) + (s[i] === "0" ? "1" : "0")
            + s.substring(i + 1);
    }

    // Add 1 to the flipped string
    let carry = 1;

    for (let i = s.length - 1; i >= 0; i--) {
        if (carry === 0)
            break;
        if (s[i] === "0") {
            s = s.substring(0, i) + "1"
                + s.substring(i + 1);
            carry = 0;
        }
        else {
            s = s.substring(0, i) + "0"
                + s.substring(i + 1);
            carry = 1;
        }
    }

    return s;
}

// Driver Code
let s = "00000101";
console.log(twosComplement(s));

Output
11111011

[Expected Approach] Traverse from Right to Left - O(n) Time and O(1) Space

The idea is to traverse from the right to find the first 1, keep it and all bits to its right unchanged, and flip all bits to its left. This directly produces the 2's complement.

Working of Approach:

  • Traverse the string from right to left to find the first occurrence of 1.
  • If no 1 exists, the string contains only 0s, so return it unchanged.
  • Keep the first 1 and all bits to its right unchanged.
  • Flip every bit to the left of that 1 to obtain the 2's complement.

Let us understand with an example:
Input: s = "00000101"

  • Start traversing the string from the right and find the first '1'. It is at the last position (index 7).
  • Keep this '1' and all bits to its right unchanged.
  • Move one position left (idx = 6) and flip every bit to the left of the first '1'.
  • The bit at index 6 changes from 0 to 1, index 5 changes from 1 to 0, and all remaining bits to the left are also flipped.
  • The final string becomes 11111011, which is the required 2's complement.
C++
#include <bits/stdc++.h>
using namespace std;

string twosComplement(string s)
{
    int idx = s.size() - 1;
    while (idx >= 0 && s[idx] == '0')
    {
        idx--;
    }
    idx--;

    while (idx >= 0)
    {

        // Flip all bits to the left of the first set bit from the right.
        s[idx] = (s[idx] == '0') ? '1' : '0';
        idx--;
    }
    return s;
}

int main()
{

    string s = "00000101";
    cout << twosComplement(s);

    return 0;
}
Java
public class GFG {
    public static String twosComplement(String s)
    {
        int idx = s.length() - 1;
        while (idx >= 0 && s.charAt(idx) == '0') {
            idx--;
        }
        idx--;

        char[] charArray = s.toCharArray();
        while (idx >= 0) {
            // Flip all bits to the left of the first set
            // bit from the right.
            charArray[idx]
                = (charArray[idx] == '0') ? '1' : '0';
            idx--;
        }
        return new String(charArray);
    }
    public static void main(String[] args)
    {
        String s = "00000101";
        System.out.println(twosComplement(s));
    }
}
Python
def twosComplement(s):
    idx = len(s) - 1
    while idx >= 0 and s[idx] == '0':
        idx -= 1
    idx -= 1

    s = list(s)
    while idx >= 0:
        # Flip all bits to the left of the first set bit from the right.
        s[idx] = '1' if s[idx] == '0' else '0'
        idx -= 1
    return ''.join(s)


if __name__ == '__main__':
    s = "00000101"
    print(twosComplement(s))
C#
using System;

public class GFG {
    public static string twosComplement(string s)
    {
        int idx = s.Length - 1;
        while (idx >= 0 && s[idx] == '0') {
            idx--;
        }
        idx--;

        char[] charArray = s.ToCharArray();
        while (idx >= 0) {
            // Flip all bits to the left of the first set
            // bit from the right.
            charArray[idx]
                = (charArray[idx] == '0') ? '1' : '0';
            idx--;
        }
        return new string(charArray);
    }

    public static void Main()
    {
        string s = "00000101";
        Console.WriteLine(twosComplement(s));
    }
}
JavaScript
function twosComplement(s)
{
    let idx = s.length - 1;
    while (idx >= 0 && s[idx] === "0") {
        idx--;
    }
    idx--;

    let sArray = s.split("");
    while (idx >= 0) {
        // Flip all bits to the left of the first set bit
        // from the right.
        sArray[idx] = sArray[idx] === "0" ? "1" : "0";
        idx--;
    }
    return sArray.join("");
}

// Driver Code
let s = "00000101";
console.log(twosComplement(s));

Output
11111011
Comment