2 's complement for a givin string using XOR | Javascript 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
function TwoscomplementbyXOR ( str ) { let n = str . length ; let check_bit = 0 ; for ( let i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == ' ' && check_bit == 0 ) { continue ; } else { if ( check_bit == 1 ) { if ( str . charAt ( i ) == ' ' ) str = str . substr ( 0 , i ) + ' ' + str . substr ( i + 1 ) ; else str = str . substr ( 0 , i ) + ' ' + str . substr ( i + 1 ) ; } check_bit = 1 ; } } if ( check_bit == 0 ) return " " + str ; else return str ; } let str = " " ; document . write ( TwoscomplementbyXOR ( str ) ) ;