Say x & y are the integer variables. The challenge is to swap them without using a temporary variable.
The solution is as simple as the problem itself:
x = x + y;
y = x - y;
x = x - y;
Update 1: Jack and Alexey pointed out a typo in my solution which has since been corrected. Please see their comments below.
The simplicity of the solution appeals to me. It clearly demonstrates the meaning of assignment operator ( "=" ).
What if they are Strings?
Note: You can use String methods in Java API.
Here is the solution:
x = x + y;
y = x.substring(0, x.indexOf(y));
x = x.substring(x.indexOf(y) + y.length());
Can you see the similarity?
Can you provide a simpler solution to either of the above?
Update 2: Robert just did (see his comment below). He pointed out that the String solution doesn't work when one string is contained in another. His solution is:
x = x + y;
y = x.substring(0, x.length() - y.length());
x = x.substring(y.length());

No comments:
Post a Comment