human
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"
How can the above be solved in Python?
assistant
#Here is code to efficient method for 2 's complement of a binary string and the other steps required.
 def findTwoscomplement ( str ) :
	n = len ( str )
	i = n - 1
	while ( i >= 0 ) :
		if ( str [ i ] == '1' ) :
			break
		i -= 1
	if ( i == - 1 ) :
		return '1' + str
'
	k = i - 1
	while ( k >= 0 ) :
		if ( str [ k ] == '1' ) :
			str = list ( str )
			str [ k ] = '0'
			str = ' ' . join ( str )
		else :
			str = list ( str )
			str [ k ] = '1'
			str = ' ' . join ( str )
		k -= 1
	return str
if __name__ == ' _ _ main _ _ ' :
	str = "00000101"
	print ( findTwoscomplement ( str ) )