Efficient method for 2 's complement of a binary string | An efficient c # program to find 2 's complement ; 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 Code
using System ; using System . Text ; class GFG { public static string findTwoscomplement ( StringBuilder str ) { int n = str . Length ; int i ; for ( i = n - 1 ; i >= 0 ; i -- ) { if ( str [ i ] == '1' ) { break ; } } if ( i == - 1 ) { return "1" + str ; } for ( int k = i - 1 ; k >= 0 ; k -- ) { if ( str [ k ] == '1' ) { str . Remove ( k , k + 1 - k ) . Insert ( k , "0" ) ; } else { str . Remove ( k , k + 1 - k ) . Insert ( k , "1" ) ; } } return str . ToString ( ) ; } public static void Main ( string [ ] args ) { StringBuilder str = new StringBuilder ( "00000101" ) ; Console . WriteLine ( findTwoscomplement ( str ) ) ; } }