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
using System ; class GFG { static void TwoscomplementbyXOR ( string str ) { int n = str . Length ; bool check_bit = false ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '0' && check_bit == false ) { continue ; } else { if ( check_bit == true ) { if ( str [ i ] == '0' ) str = str . Substring ( 0 , i ) + '1' + str . Substring ( i + 1 ) ; else str = str . Substring ( 0 , i ) + '0' + str . Substring ( i + 1 ) ; } check_bit = true ; } } if ( check_bit == false ) { Console . WriteLine ( "1" + str ) ; } else Console . WriteLine ( str ) ; } static void Main ( ) { string str = "101" ; TwoscomplementbyXOR ( str ) ; } }