Dado un número binario como una cadena, imprima sus complementos a 1 y 2.
complemento a 1 de un número binario es otro número binario que se obtiene alternando todos los bits que contiene, es decir, transformando el bit 0 en 1 y el bit 1 en 0. En el formato complemento a 1, los números positivos permanecen sin cambios. Los números negativos se obtienen tomando el complemento a 1 de sus homólogos positivos.
por ejemplo, +9 se representará como 00001001 en notación de ocho bits y -9 se representará como 11110110, que es el complemento a 1 de 00001001.
Ejemplos:
1's complement of '0111' is '1000' 1's complement of '1100' is '0011'>
complemento a 2 de un número binario es 1, sumado al complemento a 1 del número binario. En la representación en complemento a 2 de números binarios, el MSB representa el signo con un '0' usado para el signo más y un '1' usado para el signo menos. los bits restantes se utilizan para representar la magnitud. Las magnitudes positivas se representan de la misma manera que en el caso de la representación de bits de signo o complemento a 1. Las magnitudes negativas están representadas por el complemento a 2 de sus contrapartes positivas.
Ejemplos:
envoltorio de texto css
2's complement of '0111' is '1001' 2's complement of '1100' is '0100'>
Otro truco para encontrar el complemento a dos:
Paso 1: Comience desde el bit menos significativo y avance hacia la izquierda hasta encontrar un 1. Hasta que encuentre un 1, los bits permanecen iguales.
Paso 2: Una vez que haya encontrado 1, déjelo como está y ahora
Paso 3: Voltee todos los bits restantes en el 1.
Ilustración
Supongamos que necesitamos encontrar el complemento a 2 de 100100
Paso 1: Atraviese y deje que el bit permanezca igual hasta encontrar 1. Aquí x aún no se conoce. Respuesta = xxxx00 –
Paso 2 : Encontraste 1. Deja que siga igual. Respuesta = xxx100
Paso 3: Voltee todos los bits que quedan en el 1. Respuesta = 011100.
Por lo tanto, el complemento a 2 de 100100 es 011100.
Complemento de la práctica 1 recomendada ¡Pruébalo!Para el complemento a uno, simplemente necesitamos invertir todos los bits.
Para el complemento a 2, primero encontramos el complemento a uno. Recorremos el complemento a uno comenzando desde LSB (bit menos significativo) y buscamos 0. Invertimos todos los 1 (cambiamos a 0) hasta que encontramos un 0. Finalmente, invertimos el 0 encontrado. Por ejemplo, el complemento a 2 de 01000 es 11000 (tenga en cuenta que primero encontramos el complemento a uno de 01000 como 10111). Si hay todos unos (en complemento a uno), agregamos un 1 adicional en la cadena. Por ejemplo, el complemento a 2 de 000 es 1000 (el complemento a 1 de 000 es 111).
A continuación se muestra la implementación.
C++
matriz vs lista de matrices
// 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--) { si (unos[i] == '1') dos[i] = '0'; else { dos[i] = '1'; romper; } } // Si no hay interrupción: todos son 1 como en 111 o 11111; // en tal caso, agregue 1 extra al principio if (i == -1) twos = '1' + twos; corte<< '1's complement: ' << ones << endl; cout << '2's complement: ' << twos << endl; } // Driver program int main() { string bin = '1100'; printOneAndTwosComplement(bin); return 0; }> |
>
>
Java
// 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') { dos = dos.substring(0, i) + '0' + dos.substring(i + 1); } else { dos = dos.substring(0, i) + '1' + dos.substring(i + 1); romper; } } // Si no hay interrupción: todos son 1 como en 111 o 11111; // en tal caso, agrega 1 adicional al principio if (i == -1) { dos = '1' + dos; } System.out.println('Complemento a 1: ' + unos);; System.out.println('Complemento a 2: ' + dos); } // Código del controlador public static void main(String[] args) { String bin = '1100'; printOneAndTwosComplement(bin); } } // Este código fue aportado por Rajput-Ji> |
>
programas de Python
>
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> |
>
imagen de rebajas
>
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 (unos[i] == '1') { dos = dos.Subcadena(0, i) + '0' + dos.Subcadena(i + 1,dos.Longitud-( i+1)); } else { dos = dos.Subcadena(0, i) + '1' + dos.Subcadena(i + 1,dos.Longitud-(i+1)); romper; } } // Si no hay interrupción: todos son 1 como en 111 o 11111; // en tal caso, agrega 1 adicional al principio if (i == -1) { dos = '1' + dos; } Console.WriteLine('Complemento a 1: ' + unos);; Console.WriteLine('Complemento a 2: ' + dos); } // Código del controlador public static void Main(String[] args) { String bin = '1100'; printOneAndTwosComplement(bin); } } // Este código ha sido aportado por 29AjayKumar> |
>
encapsulación en java
>
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--) { si (unos[i] == '1') dos[i] = '0'; else { dos[i] = '1'; romper; } } twos = twos.join('') // Si no hay interrupción: todos son 1 como en 111 o 11111; // en tal caso, agregue 1 extra al principio if (i == -1) twos = '1' + twos; document.write( 'Complemento a 1: ' + unos + ' '); document.write( complemento de '2: ' + dos + ' '); } // Programa controlador var bin = '1100'; printOneAndTwosComplement(bin);> |
>
>
Producción:
1's complement: 0011 2's complement: 0100>
Complejidad del tiempo: En)
Espacio Auxiliar: O(1)