Created
April 3, 2020 22:38
-
-
Save asa55/78496df8daee8e694e4837f8ce67b4b1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// how to swap two numbers without using a temporary variable | |
// think about it this way | |
// x <-- a | |
// y <-- b | |
// x' <-- x - y = a - b | |
// y' <-- x' + y = ( a - b ) + b = a | |
// x''<-- y' - x' = a - ( a - b ) = b | |
#include <iostream> | |
int x = 5, y = 10; | |
void swap(int& _x, int& _y) | |
{ | |
_x = _x - _y; | |
_y = _x + _y; | |
_x = _y - _x; | |
} | |
int main () | |
{ | |
std::cout << "x: " << x << " " << "y: " << y << std::endl; | |
swap(x, y); | |
std::cout << "x: " << x << " " << "y: " << y << std::endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment