swap 2 numbers without third variable

swap 2 numbers without using third temporary variable

js:


var swap = function (a, b) {

    var a, b;

    document.querySelector('.input').innerHTML = 'a = ' + a + '; b = ' + b;

    a = a + b;

    b = a - b;

    a = a - b;

    document.querySelector('.result').innerHTML = 'a = ' + a + '; b = ' + b;

}



swap(5, 10);

html:


<h3>before swapping: <span class="input"></span></h3>

    

<h3>after swapping: <span class="result"></span></h3>

    

swapping algorithm:

<div>

    a = a + b;

    b = a - b;

    a = a - b;

</div>

Leave a Comment