human
2 's complement for a givin string using XOR | Python 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"
How can the above be solved in Python?
assistant
#Here is code to 2 's complement for a givin string using XOR and the other steps required.
 def TwoscomplementbyXOR ( str ) :
	n = len ( str )
	check_bit = 0
	i = n - 1
	s = list ( str )
	while ( i >= 0 ) :
		if ( s [ i ] == '0' and check_bit == 0 ) :
			continue
		else :
			if ( check_bit == 1 ) :
				s [ i ] = chr ( ( ord ( s [ i ] ) - 48 ) ^ 1 + 48 )
			check_bit = 1
		i -= 1
	str = " " . join ( s )
	if ( check_bit == 0 ) :
		return "1" + str
	else :
		return str
str = "101"
print ( TwoscomplementbyXOR ( str ) )