Given a binary number represented as a string, the task is to find its 1's complement and 2's complement.
- 1's complement is obtained by flipping every bit (0 -> 1 and 1 -> 0).
- 2's complement is obtained by adding 1 to the 1's complement.
Examples:
Input:
s = "0111"
Output:["1000", "1001"]Explanation:
- 1's Complement = 1000
- 2's Complement = 1001
Input:
s = "1100"
Output:["0011", "0100"]Explanation:
- 1's Complement = 0011
- 2's Complement = 0100
1's Complement
Traverse the binary string and flip every bit:
- Replace 0 with 1.
- Replace 1 with 0.
2's Complement
- Compute the 1's complement.
- Starting from the least significant bit (LSB), add 1.
- Propagate the carry until it becomes 0.
- If no 0 is found while adding 1, insert 1 at the beginning of the result.
Algorithm
- Traverse the binary string and flip every bit to obtain the 1's complement.
- Copy the 1's complement.
- Traverse from right to left to add 1.
- If no 0 is found while adding, prepend 1.
- Return both complements.
// C++ program to find 1's and 2's
// complement of a binary number
#include <bits/stdc++.h>
using namespace std;
// Function to find 1's complement
string onesComplement(string s) {
// Traverse each bit and flip it
for (char &c : s) {
if (c == '0')
c = '1';
else
c = '0';
}
return s;
}
// Function to find 2's complement
string twosComplement(string s) {
// Get 1's complement of the binary number
s = onesComplement(s);
int n = s.size();
bool carry = true;
// Add 1 to the 1's complement
for (int i = n - 1; i >= 0 && carry; i--) {
// If we find '0', change it to '1'
// and stop the addition
if (s[i] == '0') {
s[i] = '1';
carry = false;
}
// If we find '1', change it to '0'
// and continue the carry
else {
s[i] = '0';
}
}
// If carry still remains,
// add '1' at the beginning
if (carry) {
s = '1' + s;
}
return s;
}
// Function to compute both 1's and 2's complements
vector<string> findComplement(string s) {
// Compute 1's complement
string ones = onesComplement(s);
// Compute 2's complement
string twos = twosComplement(s);
return {ones, twos};
}
// Driver code
int main() {
string s = "1001";
vector<string> result = findComplement(s);
cout << "1's Complement: " << result[0] << endl;
cout << "2's Complement: " << result[1] << endl;
return 0;
}
// Java program to find 1's and 2's
// complement of a binary number
import java.util.*;
class GfG {
// Function to find 1's complement
static String onesComplement(String s) {
// Traverse each bit and flip it
StringBuilder result = new StringBuilder(s);
for (int i = 0; i < s.length(); i++) {
if (result.charAt(i) == '0')
result.setCharAt(i, '1');
else
result.setCharAt(i, '0');
}
return result.toString();
}
// Function to find 2's complement
static String twosComplement(String s) {
// Get 1's complement of the binary number
StringBuilder result = new StringBuilder(onesComplement(s));
boolean carry = true;
// Add 1 to the 1's complement
for (int i = result.length() - 1; i >= 0 && carry; i--) {
// If we find '0', change it to '1'
// and stop the addition
if (result.charAt(i) == '0') {
result.setCharAt(i, '1');
carry = false;
}
// If we find '1', change it to '0'
// and continue the carry
else {
result.setCharAt(i, '0');
}
}
// If carry still remains,
// add '1' at the beginning
if (carry) {
result.insert(0, '1');
}
return result.toString();
}
// Function to compute both 1's and 2's complements
static String[] findComplement(String s) {
// Compute 1's complement
String ones = onesComplement(s);
// Compute 2's complement
String twos = twosComplement(s);
return new String[] { ones, twos };
}
// Driver code
public static void main(String[] args) {
String s = "1001";
String[] result = findComplement(s);
System.out.println(result[0] + " " + result[1]);
}
}
# Python program to find 1's and 2's
# complement of a binary number
# Function to find 1's complement
def onesComplement(s):
# Traverse each bit and flip it
result = ""
for c in s:
if c == '0':
result += '1'
else:
result += '0'
return result
# Function to find 2's complement
def twosComplement(s):
# Get 1's complement of the binary number
result = list(onesComplement(s))
carry = True
# Add 1 to the 1's complement
for i in range(len(result) - 1, -1, -1):
if not carry:
break
# If we find '0', change it
# to '1' and stop
if result[i] == '0':
result[i] = '1'
carry = False
# If we find '1', change it
# to '0' and continue
else:
result[i] = '0'
# If carry still remains,
# add '1' at the beginning
if carry:
result.insert(0, '1')
return "".join(result)
# Function to compute both 1's and 2's complements
def findComplement(s):
# Compute 1's complement
ones = onesComplement(s)
# Compute 2's complement
twos = twosComplement(s)
return [ones, twos]
# Driver code
if __name__ == "__main__":
s = "1001"
result = findComplement(s)
print(result[0], result[1])
// C# program to find 1's and 2's
// complement of a binary number
using System;
class GfG {
// Function to find 1's complement
static string onesComplement(string s) {
// Traverse each bit and flip it
char[] result = s.ToCharArray();
for (int i = 0; i < s.Length; i++) {
if (result[i] == '0')
result[i] = '1';
else
result[i] = '0';
}
return new string(result);
}
// Function to find 2's complement
static string twosComplement(string s) {
// Get 1's complement of the binary number
char[] result = onesComplement(s).ToCharArray();
bool carry = true;
// Add 1 to the 1's complement
for (int i = result.Length - 1; i >= 0 && carry; i--) {
// If we find '0', change it to '1'
// and stop the addition
if (result[i] == '0') {
result[i] = '1';
carry = false;
}
// If we find '1', change it to '0'
// and continue the carry
else {
result[i] = '0';
}
}
// If carry still remains,
// add '1' at the beginning
if (carry) {
return "1" + new string(result);
}
return new string(result);
}
// Function to compute both 1's and 2's complements
static string[] findComplement(string s) {
// Compute 1's complement
string ones = onesComplement(s);
// Compute 2's complement
string twos = twosComplement(s);
return new string[] { ones, twos };
}
// Driver code
public static void Main() {
string s = "1001";
string[] result = findComplement(s);
Console.WriteLine(result[0] + " " + result[1]);
}
}
// JavaScript program to find 1's and 2's
// complement of a binary number
// Function to find 1's complement
function onesComplement(s) {
// Traverse each bit and flip it
let result = "";
for (let i = 0; i < s.length; i++) {
if (s[i] === '0') {
result += '1';
} else {
result += '0';
}
}
return result;
}
// Function to find 2's complement
function twosComplement(s) {
// Get 1's complement of the binary number
let result = onesComplement(s).split("");
let carry = true;
// Add 1 to the 1's complement
for (let i = result.length - 1; i >= 0 && carry; i--) {
// If we find '0', change it to '1'
// and stop the addition
if (result[i] === '0') {
result[i] = '1';
carry = false;
}
// If we find '1', change it to '0'
// and continue the carry
else {
result[i] = '0';
}
}
// If carry still remains,
// add '1' at the beginning
if (carry) {
result.unshift('1');
}
return result.join("");
}
// Function to compute both 1's and 2's complements
function findComplement(s) {
// Compute 1's complement
let ones = onesComplement(s);
// Compute 2's complement
let twos = twosComplement(s);
return [ones, twos];
}
// Driver code
let s = "1001";
let result = findComplement(s);
console.log(result[0], result[1]);
Output
0110 0111Time Complexity: O(n), as each bit is traversed at most twice—once to compute the 1's complement and once to add 1 for the 2's complement.
Auxiliary Space: O(n), as an additional string or character array is used to store the complements.