Efficient method for 2 's complement of a binary string | Method to find two 's complement ; Traverse the string to get first '1' from the last of string ; If there exists no '1' concat 1 at the starting of string ; Continue traversal after the position of first '1' ; Just flip the values ; return the modified string ; Driver method
function findTwoscomplement ( str ) { var n = str . length ; var i ; for ( i = n - 1 ; i >= 0 ; i -- ) if ( str . charAt ( i ) == ' ' ) break ; if ( i == - 1 ) return " " + str ; for ( k = i - 1 ; k >= 0 ; k -- ) { if ( str . charAt ( k ) == ' ' ) str = str . substring ( 0 , k ) + " " + str . substring ( k + 1 , str . length ) ; else str = str . substring ( 0 , k ) + " " + str . substring ( k + 1 , str . length ) ; } return str . toString ( ) ; } var str = " " ; document . write ( findTwoscomplement ( str ) ) ;