2 's complement for a givin string using XOR | Java 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
import java . util . * ; class GFG { static void TwoscomplementbyXOR ( String str ) { int n = str . length ( ) ; boolean check_bit = false ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( str . charAt ( i ) == '0' && check_bit == false ) { continue ; } else { if ( check_bit == true ) { if ( str . charAt ( 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 ) { System . out . println ( "1" + str ) ; } else System . out . println ( str ) ; } public static void main ( String [ ] args ) { String str = "101" ; TwoscomplementbyXOR ( str ) ; } }