Efficient method for 2's complement of a binary string
Last Updated :
06 Jul, 2022
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 have discussed 1's and 2's complements in below post.
1’s and 2’s complement of a Binary Number.
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.
Illustration :
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.
Implementation:
C++
// An efficient C++ program to find 2's complement
#include<bits/stdc++.h>
using namespace std;
// Function to find two's complement
string findTwoscomplement(string str)
{
int n = str.length();
// Traverse the string to get first '1' from
// the last of string
int i;
for (i = n-1 ; i >= 0 ; i--)
if (str[i] == '1')
break;
// If there exists no '1' concatenate 1 at the
// starting of string
if (i == -1)
return '1' + str;
// Continue traversal after the position of
// first '1'
for (int k = i-1 ; k >= 0; k--)
{
//Just flip the values
if (str[k] == '1')
str[k] = '0';
else
str[k] = '1';
}
// return the modified string
return str;
}
// Driver code
int main()
{
string str = "00000101";
cout << findTwoscomplement(str);
return 0;
}
Java
// An efficient Java program to find 2's complement
class Test
{
// Method to find two's complement
static String findTwoscomplement(StringBuffer str)
{
int n = str.length();
// Traverse the string to get first '1' from
// the last of string
int i;
for (i = n-1 ; i >= 0 ; i--)
if (str.charAt(i) == '1')
break;
// If there exists no '1' concat 1 at the
// starting of string
if (i == -1)
return "1" + str;
// Continue traversal after the position of
// first '1'
for (int k = i-1 ; k >= 0; k--)
{
//Just flip the values
if (str.charAt(k) == '1')
str.replace(k, k+1, "0");
else
str.replace(k, k+1, "1");
}
// return the modified string
return str.toString();
}
// Driver method
public static void main(String[] args)
{
StringBuffer str = new StringBuffer("00000101");
System.out.println(findTwoscomplement(str));
}
}
Python3
# An efficient Python 3 program to
# find 2's complement
# Function to find two's complement
def findTwoscomplement(str):
n = len(str)
# Traverse the string to get first
# '1' from the last of string
i = n - 1
while(i >= 0):
if (str[i] == '1'):
break
i -= 1
# If there exists no '1' concatenate 1
# at the starting of string
if (i == -1):
return '1'+str
# Continue traversal after the
# position of first '1'
k = i - 1
while(k >= 0):
# Just flip the values
if (str[k] == '1'):
str = list(str)
str[k] = '0'
str = ''.join(str)
else:
str = list(str)
str[k] = '1'
str = ''.join(str)
k -= 1
# return the modified string
return str
# Driver code
if __name__ == '__main__':
str = "00000101"
print(findTwoscomplement(str))
# This code is contributed by
# Sanjit_Prasad
C#
// An efficient c# program to find 2's complement
using System;
using System.Text;
class GFG
{
// Method to find two's complement
public static string findTwoscomplement(StringBuilder str)
{
int n = str.Length;
// Traverse the string to get
// first '1' from the last of string
int i;
for (i = n - 1 ; i >= 0 ; i--)
{
if (str[i] == '1')
{
break;
}
}
// If there exists no '1' concat 1
// at the starting of string
if (i == -1)
{
return "1" + str;
}
// Continue traversal after the
// position of first '1'
for (int k = i - 1 ; k >= 0; k--)
{
// Just flip the values
if (str[k] == '1')
{
str.Remove(k, k + 1 - k).Insert(k, "0");
}
else
{
str.Remove(k, k + 1 - k).Insert(k, "1");
}
}
// return the modified string
return str.ToString();
}
// Driver Code
public static void Main(string[] args)
{
StringBuilder str = new StringBuilder("00000101");
Console.WriteLine(findTwoscomplement(str));
}
}
// This code is contributed by Shrikant13
PHP
<?php
// An efficient PHP program to find 2's
// complement
// Function to find two's complement
function findTwoscomplement($str)
{
$n = strlen($str);
// Traverse the string to get first
// '1' from the last of string
$i;
for ($i = $n-1 ; $i >= 0 ; $i--)
if ($str[$i] == '1')
break;
// If there exists no '1' concatenate
// 1 at the starting of string
if ($i == -1)
return '1' + $str;
// Continue traversal after the
// position of first '1'
for ($k = $i-1 ; $k >= 0; $k--)
{
// Just flip the values
if ($str[$k] == '1')
$str[$k] = '0';
else
$str[$k] = '1';
}
// return the modified string
return $str;;
}
// Driver code
$str = "00000101";
echo findTwoscomplement($str);
// This code is contributed by jit.
?>
JavaScript
<script>
// An efficient javascript program to find 2's complement
// Method to find two's complement
function findTwoscomplement( str) {
var n = str.length;
// Traverse the string to get first '1' from
// the last of string
var i;
for (i = n - 1; i >= 0; i--)
if (str.charAt(i) == '1')
break;
// If there exists no '1' concat 1 at the
// starting of string
if (i == -1)
return "1" + str;
// Continue traversal after the position of
// first '1'
for (k = i - 1; k >= 0; k--) {
// Just flip the values
if (str.charAt(k) == '1')
str = str.substring(0,k)+"0"+str.substring(k+1, str.length);
else
str = str.substring(0,k)+"1"+str.substring(k+1, str.length);
}
// return the modified string
return str.toString();
}
// Driver method
var str = "00000101";
document.write(findTwoscomplement(str));
// This code contributed by umadevi9616
</script>
Time complexity : O(n)
Auxiliary Space : O(1)
Similar Reads
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 uncha
8 min read
Find Oneâs Complement of an Integer | Set 2 Given an integer N, find the oneâs complement of the integer. Examples: Input: N = 5Output: 2Explanation: Binary representation of 5 is "101". Its one's complement is "010" = 2. Input: N = 255Output: 0 Input: N = 26Output: 5 Approach: Already the XOR-based approach and converting the number to binar
3 min read
2's complement for a given string using XOR Given a binary string, task is to convert this string in to two's complement with the help of XOR operator. Examples: Input : 00000101Output :11111011 Input : 10010Output : 01110 We have discussed an approach in previous post to find 2's complement For 2âs complement, we first find oneâs complement.
6 min read
Count N-length Binary Strings consisting of "11" as substring Given a positive integer N, the task is to find the number of binary strings of length N which contains "11" as a substring. Examples: Input: N = 2Output: 1Explanation: The only string of length 2 that has "11" as a substring is "11". Input: N = 12Output: 3719 Approach: The idea is to derive the num
8 min read
Count of substrings of a Binary string containing only 1s Given a binary string of length N, we need to find out how many substrings of this string contain only 1s. Examples: Input: S = "0110111"Output: 9Explanation:There are 9 substring with only 1's characters. "1" comes 5 times. "11" comes 3 times. "111" comes 1 time. Input: S = "000"Output: 0 The_Appro
6 min read
Count of binary strings of given length consisting of at least one 1 Given an integer N, the task is to print the number of binary strings of length N which at least one '1'. Examples: Input: 2 Output: 3 Explanation: "01", "10" and "11" are the possible strings Input: 3 Output: 7 Explanation: "001", "011", "010", "100", "101", "110" and "111" are the possible strings
3 min read