Suponga que una variable x puede tener solo dos valores posibles a y b, y desea asignar a x un valor diferente al actual. Hágalo de manera eficiente sin usar ningún operador condicional.
Nota: No se nos permite verificar el valor actual de x.
Ejemplos:
Entrada: a = 10, b = 15, x = a
Salida: x = 15
Explicación x = 10, actualmente x tiene el valor de a (que es 10), necesitamos cambiarlo a 15.
Entrada: a = 9, b = 11, x = b
Salida: x = 9
Podríamos resolver este problema usando la condición if, pero no podemos hacerlo.
if (x == a) x = b; else x = a;
Podríamos haber usado el operador ternario, también verifica el valor actual de x y, en función de eso, asigna un nuevo valor. Así que no podemos usar este enfoque también
x = x == a ? b : a;
Pero no se nos permite verificar el valor de x, por lo que ninguna de las soluciones anteriores funciona.
Solución 1: Usando solo operadores aritméticos podemos realizar esta operación
x = a + b - x
De esta forma, el contenido de x alternará entre a y b cada vez que se ejecute
C++
// CPP program to change value of x // according to its current value. #include <bits/stdc++.h> using namespace std; // Function to alternate the values void alternate(int& a, int& b, int& x) { x = a + b - x; } // Main function int main() { int a = -10; int b = 15; int x = a; cout << "x is : " << x; alternate(a, b, x); cout << "\nAfter change "; cout << "\nx is : " << x; }
Java
// Java program to change value of x // according to its current value. import java.util.*; class solution { // Function to alternate the values static void alternate(int a, int b, int x) { x = a + b - x; System.out.println("After change"+"\n"+" x is : "+x); } // Main function public static void main(String args[]) { int a = -10; int b = 15; int x = a; System.out.println("x is : "+x); alternate(a, b, x); } }
Python3
# Python3 program to change value # of x according to its current value. # Function to alternate the values def alternate(a,b,x): x = a+b-x print("After change x is:",x) # Driver code if __name__=='__main__': a = -10 b = 15 x = a print("x is:",x) alternate(a,b,x) # This code is contributed by # Shrikant13
C#
// C# program to change value of x // according to its current value. using System; class gfg { // Function to alternate the values public void alternate(ref int a, ref int b, ref int x) //'ref' indicates the references { x = a + b - x; } } // Main function class geek { public static int Main() { gfg g = new gfg(); int a = -10; int b = 15; int x = a; Console.WriteLine("x is : {0}" , x); g.alternate(ref a, ref b, ref x); Console.WriteLine ("After change "); Console.WriteLine("x is : {0}", x); return 0; } } //This code is contributed by Soumik
PHP
<?php // PHP program to change value of x // according to its current value. // Function to alternate the values function alternate (&$a, &$b, &$x) { $x = $a + $b - $x; } // Driver Code $a = -10; $b = 15; $x = $a; echo "x is : ", $x; alternate($a, $b, $x); echo "\nAfter change "; echo "\nx is : ", $x; // This code is contributed by ajit. ?>
Javascript
<script> // javascript program to change value of x // according to its current value. // Function to alternate the values function alternate(a , b , x) { x = a + b - x; document.write("After change" + "<br/>" + " x is : " + x); } // Main function var a = -10; var b = 15; var x = a; document.write("x is : " + x+"<br/>"); alternate(a, b, x); // This code is contributed by todaysgaurav </script>
x is : -10 After change x is : 15
Complejidad de tiempo: La complejidad de tiempo de este enfoque es O(1)
Complejidad de espacio: La complejidad de espacio de este enfoque es O(1)
Solución 2: Un enfoque mejor y más eficiente es usar la operación XOR bit a bit.
x = a^b^x
C++
// CPP program to change value of x // according to its current value. #include <bits/stdc++.h> using namespace std; // Function to alternate the values void alternate(int& a, int& b, int& x) { x = a ^ b ^ x; } // Main function int main() { int a = -10; int b = 15; int x = a; cout << "x is : " << x; alternate(a, b, x); cout << "\nAfter exchange "; cout << "\nx is : " << x; return 0; }
Java
// Java program to change value of x // according to its current value. class GFG { // Function to alternate the values static int alternate(int a, int b, int x) { return x = a ^ b ^ x; } // Main function public static void main(String[] args) { int a = -10; int b = 15; int x = a; System.out.print("x is : " + x); x = alternate(a, b, x); System.out.print("\nAfter exchange "); System.out.print("\nx is : " + x); } } // This code is contributed by 29AjayKumar
Python3
# Python3 program to change value of x # according to its current value. # Function to alternate the values def alternate(a, b, x): x = a ^ b ^ x print("After exchange") print("x is", x) # Driver code a = -10 b = 15 x = a print("x is", x) alternate(a, b, x) # This code is contributed # by Shrikant13
C#
// C# program to change value of x // according to its current value. using System; public class GFG { // Function to alternate the values static int alternate(int a, int b, int x) { return x = a ^ b ^ x; } // Main function public static void Main() { int a = -10; int b = 15; int x = a; Console.Write("x is : " + x); x = alternate(a, b, x); Console.Write("\nAfter exchange "); Console.Write("\nx is : " + x); } } /*This code is contributed by Rajput-Ji*/
PHP
<?php // PHP program to change value of x // according to its current value. // Function to alternate the values function alternate(&$a, &$b, &$x) { $x = $a ^ $b ^ $x; } // Driver Code $a = -10; $b = 15; $x = $a; echo "x is : ", $x; alternate($a, $b, $x); echo "\nAfter exchange "; echo "\nx is : ", $x; // This code is contributed // by akt_mit ?>
Javascript
<script> // Javascript program to change value of x // according to its current value. // Function to alternate the values function alternate(a , b , x) { return x = a ^ b ^ x; } // Main function var a = -10; var b = 15; var x = a; document.write("x is : " + x); x = alternate(a, b, x); document.write("<br/>After exchange "); document.write("<br/>x is : " + x); // This code contributed by Rajput-Ji </script>
x is : -10 After exchange x is : 15
Complejidad de tiempo: La complejidad de tiempo de este enfoque es O(1)
Complejidad de espacio: La complejidad de espacio de este enfoque es O(1)
Solución 3:
Usando el operador de multiplicación, podemos realizar la operación:
x = un * segundo / x
De esta forma el contenido de x alternará entre a y b.
Este enfoque tiene un solo paso:
Paso 1: x = a * b / x
C++
// CPP program to change value of x // according to its current value. #include <bits/stdc++.h> using namespace std; // Function to alternate the values void alternate(int& a, int& b, int& x) { x = a * b / x; } // Main function int main() { int a = -10; int b = 15; int x = a; cout << "x is : " << x; alternate(a, b, x); cout << "\nAfter change "; cout << "\nx is : " << x; } //This code is contributed by phasing17
Javascript
// JavaScript program to change value of x // according to its current value. // Function to alternate the values function alternate(a, b,x ) { x = a * b / x; return x; } // Main function let a = -10; let b = 15; let x = a; console.log("x is : " + x); x = alternate(a, b, x); console.log("After change "); console.log("x is : " + x); // This code is contributed by phasing17
Producción:
x is : -10 After exchange x is : 15
Complejidad de tiempo: La complejidad de tiempo de este enfoque es O(1)
Espacio auxiliar: La complejidad de espacio de este enfoque es O(1)
Publicación traducida automáticamente
Artículo escrito por Shubham__Ranjan y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA