0

Is it possible to swap two numbers using function in Java?

9th May 2019, 9:25 AM
Shubham Tandale
Shubham Tandale - avatar
5 ответов
+ 3
Prokopios Poulimenos A method can not return two values, so I would use an array for the two numbers: https://code.sololearn.com/cb2en41ZAjw7/?ref=app
10th May 2019, 12:39 AM
Denise Roßberg
Denise Roßberg - avatar
+ 1
Solution 1 : Use a third variable and do the following : temp = x; x = y; y = temp; -- ----------------------- Solution 2 : Without temporary variable x = x + y; y = x - y; x = x - y; -- ----------------------- Solution 3 : With bitwise operator x = x ^ y; y = x ^ y; x = x ^ y;
9th May 2019, 9:46 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar
9th May 2019, 10:07 AM
Prokopios Poulimenos
Prokopios Poulimenos - avatar
+ 1
Prokopios Poulimenos: solution 1 is correct solution 2 may cause operator overflow (it's computer algebra, not math - range is limited) and x,y might be objects? solution 3 - no idea why this should work (e.g. x = 1 and y = 0) and depends on number encoding, but what if y,x are no numbers?
9th May 2019, 10:16 AM
Daniel Adam
Daniel Adam - avatar
0
Sorry but I am asking about using function I mean pass two variables to function to get swapped
9th May 2019, 9:51 AM
Shubham Tandale
Shubham Tandale - avatar