2 's complement for a givin string using XOR | C ++ program to find 2 's complement using XOR. ; A flag used to find if a 1 bit is seen or not . ; xor operator is used to flip the ; bits after converting in to ASCII values ; if there is no 1 in the string so just add 1 in starting of string and return ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; string TwoscomplementbyXOR ( string str ) { int n = str . length ( ) ; bool check_bit = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '0' && check_bit == 0 ) { continue ; } else { if ( check_bit == 1 ) str [ i ] = ( str [ i ] - '0' ) ^ 1 + '0' ; check_bit = 1 ; } } if ( check_bit == 0 ) return "1" + str ; else return str ; } int main ( ) { string str = "101" ; cout << TwoscomplementbyXOR ( str ) ; return 0 ; }