Intercambiar tres variables sin usar una variable temporal

Dadas tres variables, a, b y c, intercámbielas sin variable temporal.
Ejemplo : 
 

Input  : a = 10, b = 20 and c = 30
Output : a = 30, b = 10 and c = 20

Método 1 (usando operadores aritméticos) 
La idea es obtener la suma en uno de los dos números dados. Luego, los números se pueden intercambiar usando la suma y la resta de la suma. 
Ya hemos discutido el intercambio de dos variables aquí . Podemos extender los mismos enfoques 
 

C++

// C++ program to swap three variables
// without using temporary variable.
#include <iostream>
using namespace std;
 
// Assign c's value to a, a's value to b and
// b's value to c.
void swapThree(int &a, int &b, int &c)
{
    // Store sum of all in a
    a = a + b + c;  // (a = 60)
 
    // After this, b has value of a
    b = a - (b+c);  // (b = 60 – (20+30) =10)
 
    // After this, c has value of b
    c = a - (b+c);  // (c = 60 – (10 + 30) = 20)
 
    // After this, a has value of c
    a = a - (b+c);   //(a = 60 – (10 + 20) = 30)
}
 
// Driver code
int main()
{
    int a = 10, b = 20, c = 30;
 
    cout << "Before swapping a = " << a << ", b = "
         << b << ", c = " << c << endl;
 
    swapThree(a, b, c);
 
    cout << "After swapping a = " << a << ", b = "
         << b << ", c = " << c << endl;
 
    return 0;
}

Java

// Java program to swap three variables
// without using temporary variable.
class GFG
{
    static int a, b, c;
 
    // Assign c's value to a, a's value
    // to b and b's value to c.
    static void swapThree()
    {
             
        // Store sum of all in a
        // (a = 60)
        a = a + b + c;
     
        // After this, b has value of a
        // (b = 60 - (20 + 30) = 10)
        b = a - (b + c);
     
        // After this, c has value of b
        // (c = 60 - (10 + 30) = 20)
        c = a - (b + c);
     
        // After this, a has value of c
        // (a = 60 - (10 + 20) = 30)
        a = a - (b + c);
    }
 
    // Driver Code
    public static void main(String []args)
    {
        a = 10; b = 20; c = 30;
        System.out.println("Before swapping a = " +
                                 a + ", b = " + b +
                                     ", c = " + c);
                             
        // Calling Function
        swapThree();
 
        System.out.println("After swapping a = " +
                                a + ", b = " + b +
                                    ", c = " + c);
    }
}
 
// This code is contributed by PrinciRaj1992

Python3

# python 3 program to swap three variables
# without using temporary variable.
 
# Assign c's value to a, a's value to b and
# b's value to c.
def swapThree(a, b, c):
    # Store sum of all in a
    a = a + b + c # (a = 60)
 
    # After this, b has value of a
    b = a - (b+c) # (b = 60 – (20+30) =10)
 
    # After this, c has value of b
    c = a - (b+c) # (c = 60 – (10 + 30) = 20)
 
    # After this, a has value of c
    a = a - (b+c) #(a = 60 – (10 + 20) = 30)
     
    print("After swapping a =",a,", b =",b,", c =",c)
 
# Driver code
if __name__ == '__main__':
    a = 10
    b = 20
    c = 30
 
    print("Before swapping a =",a,", b =",b,", c =",c)
 
    swapThree(a, b, c)
     
# This code is contributed by
# Surendra_Gangwar

C#

// C# program to swap three variables
// without using temporary variable.
using System;
 
class GFG
{
 
    // Assign c's value to a, a's value
    // to b and b's value to c.
    static void swapThree(ref int a,
                        ref int b,
                        ref int c)
    {
    // Store sum of all in a
    // (a = 60)
        a = a + b + c;
 
    // After this, b has value of a
    // (b = 60 – (20 + 30) = 10)
        b = a - (b + c);
 
    // After this, c has value of b
    // (c = 60 – (10 + 30) = 20)
        c = a - (b + c);
 
    // After this, a has value of c
    // (a = 60 – (10 + 20) = 30)
        a = a - (b + c);
    }
 
    // Driver Code
    static void Main(String []args)
    {
         
        int a = 10, b = 20, c = 30;
        Console.WriteLine("Before swapping a = " +
                                a + ", b = " + b +
                                    ", c = " + c);
                             
        // Calling Function
        swapThree(ref a, ref b,ref c);
 
        Console.Write("After swapping a = " +
                           a + ", b = " + b +
                               ", c = " + c);
    }
}
 
// This code is contributed by Sam007.

PHP

<?php
// PHP program to swap three
// variables without using
// temporary variable.
 
// Assign c's value to a,
// a's value to b and
// b's value to c.
function swapThree(&$a, &$b, &$c)
{
    // Store sum of all in a
    $a = $a + $b + $c; // (a = 60)
 
    // After this, b has value of a
    // (b = 60 – (20+30) =10)
    $b = $a - ($b + $c);
 
    // After this, c has value of b
    // (c = 60 – (10 + 30) = 20)
    $c = $a - ($b + $c);
 
    // After this, a has value of c
    //(a = 60 – (10 + 20) = 30)
    $a = $a - ($b + $c);
}
 
// Driver Code
$a = 10; $b = 20; $c = 30;
 
echo "Before swapping a = " , $a ,
         ", b = ", $b , ", c = " ,
                         $c ,"\n";
 
swapThree($a, $b, $c);
 
echo "After swapping a = ",$a ,
                 ", b = ", $b ,
           ", c = ", $c , "\n";
 
// This code is contributed by ajit
?>

Javascript

<script>
// javascript program to swap three variables
// without using temporary variable.
 
let a, b, c;
 
// Assign c's value to a, a's value
// to b and b's value to c.
function swapThree()
{
         
    // Store sum of all in a
    // (a = 60)
    a = a + b + c;
 
    // After this, b has value of a
    // (b = 60 - (20 + 30) = 10)
    b = a - (b + c);
 
    // After this, c has value of b
    // (c = 60 - (10 + 30) = 20)
    c = a - (b + c);
 
    // After this, a has value of c
    // (a = 60 - (10 + 20) = 30)
    a = a - (b + c);
}
 
// Driver Code
a = 10; b = 20; c = 30;
document.write("Before swapping a = " +
                         a + ", b = " + b +
                             ", c = " + c);
                     
// Calling Function
swapThree();
 
document.write("<br>After swapping a = " +
                        a + ", b = " + b +
                            ", c = " + c);
 
// This code contributed by Princi Singh
</script>

Producción : 
 

Before swapping a = 10, b = 20, c = 30
After swapping a = 30, b = 10, c = 20

Complejidad de tiempo: O(1)

Espacio Auxiliar: O(1)

Gracias a Mazhar MIK por sugerir este método.
Método 2 (usando XOR bit a bit) 
El operador XOR bit a bit se puede usar para intercambiar tres variables. La idea es similar al método 1. Primero almacenamos XOR de todos los números en ‘a’. Luego obtenemos números individuales haciendo XOR de esto con otros dos números.
 

C++

// C++ program to swap three variables
// without using temporary variable
#include <iostream>
using namespace std;
 
// Assign c's value to a, a's value to b and
// b's value to c.
void swapThree(int &a, int &b, int &c)
{
    // Store XOR of all in a
    a = a ^ b ^ c;
 
    // After this, b has value of a
    b = a ^ b ^ c;
 
    // After this, c has value of b
    c = a ^ b ^ c;
 
    // After this, a has value of c
    a = a ^ b ^ c;
}
 
// Driver code
int main()
{
    int a = 10, b = 20, c = 30;
 
    cout << "Before swapping a = " << a << ", b = "
         << b << ", c = " << c << endl;
 
    swapThree(a, b, c);
 
    cout << "After swapping a = " << a << ", b = "
         << b << ", c = " << c << endl;
 
    return 0;
}

Java

// Java program to swap three variables
// without using temporary variable.
class GFG
{
    static int a, b, c;
 
    // Assign c's value to a, a's value
    // to b and b's value to c.
    static void swapThree()
    {
        // Store XOR of all in a
        a = a ^ b ^ c;
 
        // After this, b has value of a
        b = a ^ b ^ c;
 
        // After this, c has value of b
        c = a ^ b ^ c;
 
        // After this, a has value of c
        a = a ^ b ^ c;
    }
 
    // Driver Code
    public static void main(String[] args)
    {
        a = 10;
        b = 20;
        c = 30;
        System.out.println("Before swapping a = " + a +
                           ", b = " + b + ",c = " + c);
 
        // Calling Function
        swapThree();
        System.out.println("After swapping a = " + a +
                           ", b = " + b + ", c = " + c);
    }
}
 
// This code is contributed by Rajput-Ji

Python3

# Python program to swap three variables
# without using temporary variable
 
# Assign c's value to a, a's value to b and
# b's value to c.
def swapThree(a, b, c) :
 
    # Store XOR of all in a
    a[0] = a[0] ^ b[0] ^ c[0]
 
    # After this, b has value of a[0]
    b[0] = a[0] ^ b[0] ^ c[0]
 
    # After this, c has value of b
    c[0] = a[0] ^ b[0] ^ c[0]
 
    # After this, a[0] has value of c
    a[0] = a[0] ^ b[0] ^ c[0]
 
# Driver code
a, b, c = [10], [20], [30]
 
print("Before swapping a = ", a[0],
    ", b = ", b[0], ", c = ", c[0])
 
swapThree(a, b, c)
 
print("After swapping a = ", a[0],
   ", b = ", b[0], ", c = ", c[0])
 
# This code is contributed by SHUBHAMSINGH10

C#

// C# program to swap three variables
// without using temporary variable.
using System;
 
class GFG
{
     
    // Assign c's value to a, a's value
    // to b and b's value to c.
    static void swapThree(ref int a,
                          ref int b,
                          ref int c)
    {
    // Store XOR of all in a
        a = a ^ b ^ c;
 
    // After this, b has value of a
        b = a ^ b ^ c;
 
    // After this, c has value of b
        c = a ^ b ^ c;
 
    // After this, a has value of c
        a = a ^ b ^ c;
    }
 
    // Driver Code
    static void Main(String []args)
    {
         
    int a = 10, b = 20, c = 30;
        Console.WriteLine( "Before swapping a = " +
                            a +", b = " + b +
                               ",c = " + c);
                              
         
        // Calling Function
        swapThree(ref a, ref b,ref c);
 
         
        Console.Write("After swapping a = " +
                       a +", b = " + b +
                       ", c = " + c);
                        
    }
}
 
// This code is contributed by Sam007.

PHP

<?php
//PHP program to swap three variables
// without using temporary variable
 
// Assign c's value to a, a's value to b and
// b's value to c.
 
function swapThree(&$a, &$b, &$c)
{
    // Store XOR of all in a
    $a = $a ^ $b ^ $c;
 
    // After this, b has value of a
    $b = $a ^ $b ^ $c;
 
    // After this, c has value of b
    $c = $a ^ $b ^ $c;
 
    // After this, a has value of c
    $a = $a ^ $b ^ $c;
}
 
// Driver code
 
    $a = 10; $b = 20; $c = 30;
 
    echo  "Before swapping a = " , $a , ", b = ",
         $b , ", c = " , $c ,"\n";
 
    swapThree($a, $b, $c);
 
    echo "After swapping a = ", $a , ", b = ",
         $b , ", c = " , $c ,"\n";
 
     
#This code is contributed by ajit
?>

Javascript

<script>
 
// javascript program to swap three variables
// without using temporary variable.
 
var a, b, c;
 
// Assign c's value to a, a's value
// to b and b's value to c.
function swapThree()
{
    // Store XOR of all in a
    a = a ^ b ^ c;
 
    // After this, b has value of a
    b = a ^ b ^ c;
 
    // After this, c has value of b
    c = a ^ b ^ c;
 
    // After this, a has value of c
    a = a ^ b ^ c;
}
 
// Driver Code
a = 10;
b = 20;
c = 30;
document.write("Before swapping a = " + a +
                   ", b = " + b + ", c = " + c);
 
// Calling Function
swapThree();
document.write("<br>")
document.write("After swapping a = " + a +
                   ", b = " + b + ", c = " + c);
 
// This code contributed by Princi Singh
 
</script>

Producción: 
 

Before swapping a = 10, b = 20, c = 30
After swapping a = 30, b = 10, c = 20

Complejidad de tiempo: O(1)

Espacio Auxiliar: O(1)

El método 1 provoca un desbordamiento para valores grandes de a, b y c, mientras que el método 2 no lo hace.
Este artículo es una contribución de Shubham . Si te gusta GeeksforGeeks y te gustaría contribuir, también puedes escribir un artículo usando write.geeksforgeeks.org o enviar tu artículo por correo a review-team@geeksforgeeks.org. Vea su artículo que aparece en la página principal de GeeksforGeeks y ayude a otros Geeks.
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
 

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *