Efficient method for 2 's complement of a binary string | Function to find two 's complement ; Traverse the string to get first '1' from the last of string ; If there exists no '1' concatenate 1 at the starting of string ; Continue traversal after the position of first '1 ; Just flip the values ; return the modified string ; Driver code
def findTwoscomplement ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE i = n - 1 NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( str [ i ] == '1' ) : NEW_LINE INDENT break NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT if ( i == - 1 ) : NEW_LINE INDENT return '1' + str NEW_LINE DEDENT DEDENT ' NEW_LINE INDENT k = i - 1 NEW_LINE while ( k >= 0 ) : NEW_LINE INDENT if ( str [ k ] == '1' ) : NEW_LINE INDENT str = list ( str ) NEW_LINE str [ k ] = '0' NEW_LINE str = ' ' . join ( str ) NEW_LINE DEDENT else : NEW_LINE INDENT str = list ( str ) NEW_LINE str [ k ] = '1' NEW_LINE str = ' ' . join ( str ) NEW_LINE DEDENT k -= 1 NEW_LINE DEDENT return str NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT str = "00000101" NEW_LINE print ( findTwoscomplement ( str ) ) NEW_LINE DEDENT