1’s and 2’s complement of a Binary Number
Given a binary number s represented as a string. The task is to return its 1’s complement and 2’s complement in form of an array as [onesComplement, twosComplement].
The 1’s complement of a binary number is obtained by flipping all its bits. 0 becomes 1, and 1 becomes 0. Positive numbers remain unchanged whereas negative numbers are represented by taking the 1’s complement of their positive counterparts.
For example, in 8-bit notation:
- +9 is represented as 00001001.
- -9 is represented as 11110110, which is the 1’s complement of 00001001.
Examples:
Input: s = “0111”
Output: 1000
Explanation: Each bit is flipped, i.e. 0 becomes 1, and 1 becomes 0.Input: s= “1100”
Output: 0011
Explanation: Each bit is flipped, i.e. 0 becomes 1, and 1 becomes 0.
The 2’s complement of a binary number is obtained by finding the 1’s complement (flipping all bits) and then adding 1 to the result. In 2’s complement representation, the Most Significant Bit (MSB) represents the sign. A 0 indicates a positive number, while a 1 indicates a negative number. The remaining bits represent the magnitude.
Positive numbers are represented the same way as in 1’s complement and sign-bit representation. Negative numbers are obtained by taking the 2’s complement of their positive counterparts.
Examples:
Input: s = “0111”
Output: 1001
Explanation: Find 1’s complement -> 1000, then add 1 -> 1000 + 1 = 1001Input: “1100”
Output: 0100
Explanation: Find 1’s complement -> 0011, then add 1 -> 0011 + 1 = 0100
The idea is to first compute the 1’s complement by flipping each bit of the binary string. Then, to find the 2’s complement, we add 1 to the 1’s complement, starting from the rightmost bit. If all bits are flipped, an extra ‘1’ is added at the beginning. This ensures correct representation in signed binary numbers.
Steps to implement the above idea:
- onesComplement() iterates through s and flip each ‘0’ to ‘1’ and ‘1’ to ‘0’.
- twosComplement() calls onesComplement, then add 1 to the least significant bit.
- Traverse s from right to left, flipping ‘1’ to ‘0’ until the first ‘0’, which is changed to ‘1’.
- If no ‘0’ is found, prepend ‘1’ to s to maintain the correct two’s complement representation.
// 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();
// Add 1 to the 1's complement
for (int i = n - 1; i >= 0; i--) {
// If we find '0', change it
// to '1' and stop
if (s[i] == '0') {
s[i] = '1';
break;
}
// If we find '1', change it
// to '0' and continue
else {
s[i] = '0';
}
}
// If all bits were flipped, we need
// to add an extra '1'
// at the beginning to maintain
// correct two's complement
if (s[0] == '0') {
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 << result[0] << " " << 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 (s.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
s = onesComplement(s);
int n = s.length();
// Add 1 to the 1's complement
StringBuilder result = new StringBuilder(s);
for (int i = n - 1; i >= 0; i--) {
// If we find '0', change it
// to '1' and stop
if (s.charAt(i) == '0') {
result.setCharAt(i, '1');
break;
}
// If we find '1', change it
// to '0' and continue
else {
result.setCharAt(i, '0');
}
}
// If all bits were flipped, we need
// to add an extra '1'
// at the beginning to maintain
// correct two's complement
if (result.charAt(0) == '0') {
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
s = onesComplement(s)
n = len(s)
# Add 1 to the 1's complement
result = list(s)
for i in range(n - 1, -1, -1):
# If we find '0', change it
# to '1' and stop
if s[i] == '0':
result[i] = '1'
break
# If we find '1', change it
# to '0' and continue
else:
result[i] = '0'
# If all bits were flipped, we need
# to add an extra '1'
# at the beginning to maintain
# correct two's complement
if result[0] == '0':
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 (s[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
s = onesComplement(s);
int n = s.Length;
// Add 1 to the 1's complement
char[] result = s.ToCharArray();
for (int i = n - 1; i >= 0; i--) {
// If we find '0', change it
// to '1' and stop
if (s[i] == '0') {
result[i] = '1';
break;
}
// If we find '1', change it
// to '0' and continue
else {
result[i] = '0';
}
}
// If all bits were flipped, we need
// to add an extra '1'
// at the beginning to maintain
// correct two's complement
if (result[0] == '0') {
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
s = onesComplement(s);
let n = s.length;
let result = s.split("");
// Add 1 to the 1's complement
for (let i = n - 1; i >= 0; i--) {
// If we find '0', change it
// to '1' and stop
if (s[i] === '0') {
result[i] = '1';
break;
}
// If we find '1', change it
// to '0' and continue
else {
result[i] = '0';
}
}
// If all bits were flipped, we need
// to add an extra '1'
// at the beginning to maintain
// correct two's complement
if (result[0] === '0') {
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 10111
Time Complexity: O(n), as each bit is processed once.
Space Complexity: O(1), as no extra space is used.