Tuesday, May 08, 2012

swapping two variables without using the third one

Case 1 : Variable is a number
If X = 4, Y = 2 We need to swap the values of X and Y Traditional approach involves a temporary variable
int x=4; y=2;
int temp;
temp = y;
y = x;
x = temp;

Optimal approach

X = X + Y; (X = 4+2 =6)
Y = X - Y; (Y = 6-2 =4)
X = X - Y; (X = 4-2 =2)

Final result : X= 2, Y=4

1 comment:

Best Flights Booking For USA said...

You may think of many ways to save money on your travel bookings. If you're looking for Fares Match Flights deals, you can select the essential and vital stuff to ensure that your holiday booking is at a low cost. You can make sure that your journey is affordable by doing this.
Travel Destinations:
Best Travel Plan
Cheap Flights To Denver
Cheap Flights To Dallas
Cheap Flights To New York
Cheap Flights To San Antonio
Cheap Flights To San Jose
Cheap Flights To Las Vegas
Cheap Flights To Honolulu