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
def TwoscomplementbyXOR ( str ) : NEW_LINE INDENT n = len ( str ) NEW_LINE check_bit = 0 NEW_LINE i = n - 1 NEW_LINE s = list ( str ) NEW_LINE while ( i >= 0 ) : NEW_LINE INDENT if ( s [ i ] == '0' and check_bit == 0 ) : NEW_LINE INDENT continue NEW_LINE DEDENT else : NEW_LINE INDENT if ( check_bit == 1 ) : NEW_LINE INDENT s [ i ] = chr ( ( ord ( s [ i ] ) - 48 ) ^ 1 + 48 ) NEW_LINE DEDENT check_bit = 1 NEW_LINE DEDENT i -= 1 NEW_LINE DEDENT str = " " . join ( s ) NEW_LINE if ( check_bit == 0 ) : NEW_LINE INDENT return "1" + str NEW_LINE DEDENT else : NEW_LINE INDENT return str NEW_LINE DEDENT DEDENT str = "101" NEW_LINE print ( TwoscomplementbyXOR ( str ) ) NEW_LINE