Complemento a 1 e 2 di un numero binario

Dato un numero binario come una stringa, stampa i suoi complementi 1 e 2.

complemento di 1 di un numero binario è un altro numero binario ottenuto alternando tutti i bit al suo interno, ovvero trasformando il bit 0 in 1 e il bit 1 in 0. Nel formato del complemento a 1, i numeri positivi rimangono invariati. I numeri negativi si ottengono prendendo il complemento a 1 delle controparti positive.

ad esempio +9 sarà rappresentato come 00001001 nella notazione a otto bit e -9 sarà rappresentato come 11110110, che è il complemento a 1 di 00001001.

Esempi:

1's complement of '0111' is '1000' 1's complement of '1100' is '0011' 

complemento a 2 di un numero binario è 1, sommato al complemento a 1 del numero binario. Nella rappresentazione in complemento a 2 dei numeri binari, l'MSB rappresenta il segno con uno '0' utilizzato per il segno più e un '1' utilizzato per il segno meno. i bit rimanenti vengono utilizzati per rappresentare la magnitudo. le grandezze positive sono rappresentate allo stesso modo del caso della rappresentazione con bit di segno o in complemento a 1. Le grandezze negative sono rappresentate dal complemento a 2 delle loro controparti positive.

Esempi:

2's complement of '0111' is '1001' 2's complement of '1100' is '0100' 

Un altro trucco per trovare il complemento a due:

Passo 1: Inizia dal bit meno significativo e vai a sinistra finché non trovi un 1. Finché non trovi 1, i bit rimangono gli stessi

Passo 2: Una volta trovato 1, lascialo così com'è e ora

Passaggio 3: Capovolgi tutti i bit rimasti in 1.

Illustrazione

Supponiamo di dover trovare il complemento a 2 di 100100

Passo 1: Attraversa e lascia che la punta rimanga la stessa finché non trovi 1. Qui x non è ancora noto. Risposta = xxxx00 –

Passo 2 : Hai trovato 1. Lascia che rimanga lo stesso. Risposta = xxx100

Passaggio 3: Capovolgi tutti i bit rimasti in 1. Risposta = 011100.

Quindi il complemento a 2 di 100100 è 011100.

Complemento consigliato della Pratica 1 Provalo!

Per il proprio complemento, dobbiamo semplicemente invertire tutti i bit.
Per il complemento a 2, troviamo prima il complemento a uno. Attraversiamo il complemento a uno partendo da LSB (bit meno significativo) e cerchiamo 0. Invertiamo tutti gli 1 (cambiamo in 0) finché non troviamo uno 0. Infine, invertiamo lo 0 trovato. Ad esempio, il complemento a 2 di 01000 è 11000 (nota che prima troviamo il complemento di 01000 come 10111). Se ci sono tutti 1 (in complemento a uno), aggiungiamo un 1 in più nella stringa. Ad esempio, il complemento di 2 di 000 è 1000 (il complemento di 1 di 000 è 111).

Di seguito è riportata l'implementazione.

C++




// C++ program to print 1's and 2's complement of> // a binary number> #include> using> namespace> std;> > // Returns '0' for '1' and '1' for '0'> char> flip(> char> c) {> return> (c ==> '0'> )?> '1'> :> '0'> ;}> > // Print 1's and 2's complement of binary number> // represented by 'bin'> void> printOneAndTwosComplement(string bin)> {> > int> n = bin.length();> > int> i;> > > string ones, twos;> > ones = twos => ''> ;> > > // for ones complement flip every bit> > for> (i = 0; i ones += flip(bin[i]); // for two's complement go from right to left in // ones complement and if we get 1 make, we make // them 0 and keep going left when we get first // 0, make that 1 and go out of loop twos = ones; for (i = n - 1; i>= 0; i--) { if (uno[i] == '1') due[i] = '0'; else { due[i] = '1'; rottura; } } // Se non c'è interruzione: tutti sono 1 come in 111 o 11111; // in tal caso, aggiungi 1 extra all'inizio if (i == -1) due = '1' + due; cout < < '1's complement: ' < < ones < < endl; cout < < '2's complement: ' < < twos < < endl; } // Driver program int main() { string bin = '1100'; printOneAndTwosComplement(bin); return 0; }>

Giava




// Java program to print 1's and 2's complement of> // a binary number> > class> GFG> {> > > // Returns '0' for '1' and '1' for '0'> > static> char> flip(> char> c)> > {> > return> (c ==> '0'> ) ?> '1'> :> '0'> ;> > }> > > // Print 1's and 2's complement of binary number> > // represented by 'bin'> > static> void> printOneAndTwosComplement(String bin)> > {> > int> n = bin.length();> > int> i;> > > String ones => ''> , twos => ''> ;> > ones = twos => ''> ;> > > // for ones complement flip every bit> > for> (i => 0> ; i { ones += flip(bin.charAt(i)); } // for two's complement go from right to left in // ones complement and if we get 1 make, we make // them 0 and keep going left when we get first // 0, make that 1 and go out of loop twos = ones; for (i = n - 1; i>= 0; i--) { if (ones.charAt(i) == '1') { due = due.sottostringa(0, i) + '0' + due.sottostringa(i + 1); } else { due = due.sottostringa(0, i) + '1' + due.sottostringa(i + 1); rottura; } } // Se non c'è interruzione: tutti sono 1 come in 111 o 11111; // in tal caso, aggiungi 1 extra all'inizio if (i == -1) { due = '1' + due; } System.out.println(complemento di '1: ' + unità);; System.out.println(complemento di '2: ' + due); } // Codice driver public static void main(String[] args) { String bin = '1100'; printComplementoUnoEDue(bin); } } // Questo codice è stato fornito da Rajput-Ji>

Python3




# Python3 program to print 1's and 2's> # complement of a binary number> > # Returns '0' for '1' and '1' for '0'> def> flip(c):> > return> '1'> if> (c> => => '0'> )> else> '0'> > # Print 1's and 2's complement of> # binary number represented by 'bin'> def> printOneAndTwosComplement(> bin> ):> > > n> => len> (> bin> )> > ones> => ''> > twos> => ''> > > # for ones complement flip every bit> > for> i> in> range> (n):> > ones> +> => flip(> bin> [i])> > > # for two's complement go from right> > # to left in ones complement and if> > # we get 1 make, we make them 0 and> > # keep going left when we get first> > # 0, make that 1 and go out of loop> > ones> => list> (ones.strip(''))> > twos> => list> (ones)> > for> i> in> range> (n> -> 1> ,> -> 1> ,> -> 1> ):> > > if> (ones[i]> => => '1'> ):> > twos[i]> => '0'> > else> :> > twos[i]> => '1'> > break> > > i> -> => 1> > # If No break : all are 1 as in 111 or 11111> > # in such case, add extra 1 at beginning> > if> (i> => => -> 1> ):> > twos.insert(> 0> ,> '1'> )> > > print> (> '1's complement: '> ,> *> ones, sep> => '')> > print> (> '2's complement: '> ,> *> twos, sep> => '')> > # Driver Code> if> __name__> => => '__main__'> :> > bin> => '1100'> > printOneAndTwosComplement(> bin> .strip(''))> > # This code is contributed> # by SHUBHAMSINGH10>

C#




// C# program to print 1's and 2's complement of> // a binary number> using> System;> > class> GFG> {> > > // Returns '0' for '1' and '1' for '0'> > static> char> flip(> char> c)> > {> > return> (c ==> '0'> ) ?> '1'> :> '0'> ;> > }> > > // Print 1's and 2's complement of binary number> > // represented by 'bin'> > static> void> printOneAndTwosComplement(String bin)> > {> > int> n = bin.Length;> > int> i;> > > String ones => ''> , twos => ''> ;> > ones = twos => ''> ;> > > // for ones complement flip every bit> > for> (i = 0; i { ones += flip(bin[i]); } // for two's complement go from right to left in // ones complement and if we get 1 make, we make // them 0 and keep going left when we get first // 0, make that 1 and go out of loop twos = ones; for (i = n - 1; i>= 0; i--) { if (uno[i] == '1') { due = due.Sottostringa(0, i) + '0' + due.Sottostringa(i + 1,due.Lunghezza-( i+1)); } else { due = due.Sottostringa(0, i) + '1' + due.Sottostringa(i + 1,due.Lunghezza-(i+1)); rottura; } } // Se non c'è interruzione: tutti sono 1 come in 111 o 11111; // in tal caso, aggiungi 1 extra all'inizio if (i == -1) { due = '1' + due; } Console.WriteLine('complemento di 1: ' + unità);; Console.WriteLine(complemento di '2: ' + due); } // Codice driver public static void Main(String[] args) { String bin = '1100'; printComplementoUnoEDue(bin); } } // Questo codice è stato fornito da 29AjayKumar>

Javascript




> > // Javascript program to print 1's and 2's complement of> // a binary number> > // Returns '0' for '1' and '1' for '0'> function> flip (c) {> return> (c ==> '0'> )?> '1'> :> '0'> ;}> > // Print 1's and 2's complement of binary number> // represented by 'bin'> function> printOneAndTwosComplement(bin)> {> > var> n = bin.length;> > var> i;> > > var> ones, twos;> > ones = twos => ''> ;> > > // for ones complement flip every bit> > for> (i = 0; i ones += flip(bin[i]); // for two's complement go from right to left in // ones complement and if we get 1 make, we make // them 0 and keep going left when we get first // 0, make that 1 and go out of loop twos = ones; twos = twos.split('') for (i = n - 1; i>= 0; i--) { if (uno[i] == '1') due[i] = '0'; else { due[i] = '1'; rottura; } } due = due.join('') // Se non c'è interruzione: tutti sono 1 come in 111 o 11111; // in tal caso, aggiungi 1 extra all'inizio if (i == -1) due = '1' + due; document.write( Complemento di '1: ' + unità + ' '); document.write( Complemento di '2: ' + due + ' '); } // Programma driver var bin = '1100'; printComplementoUnoEDue(bin);>

Produzione:

1's complement: 0011 2's complement: 0100 

Complessità temporale: SU)

Spazio ausiliario: O(1)