-
September 27th, 2016, 12:42 AM
#1
How to Swap two numbers without using third variable in Java?
How to Swap two numbers without using third variable in Java?
-
September 27th, 2016, 02:51 AM
#2
Re: How to Swap two numbers without using third variable in Java?
A quick google search provides plenty of answers! Consider
Code:
int x = 10, y = 5;
// Code to swap 'x' and 'y'
x = x + y; // x now becomes 15
y = x - y; // y becomes 10
x = x - y; // x becomes 5
Note that this may be imprecise for non-integer numbers due to rounding errors.
For a detailed discussion see
http://javarevisited.blogspot.co.uk/...-tutorial.html
All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!
C++23 Compiler: Microsoft VS2022 (17.6.5)
-
July 24th, 2018, 02:25 AM
#3
Re: How to Swap two numbers without using third variable in Java?
You can refer below resource for swapping two numbers,
https://www.flowerbrackets.com/java-...p-two-numbers/
Last edited by sidsomashak; September 13th, 2019 at 03:47 AM.
Reason: corrected spelling mistake
-
July 24th, 2018, 03:28 AM
#4
Re: How to Swap two numbers without using third variable in Java?
Originally Posted by arshi1586
How to Swap two numbers without using third variable in Java?
The most "famous" way to do that I suppose is the XOR Swap Algorithm,
https://en.wikipedia.org/wiki/XOR_swap_algorithm
The algorithm is language independent and it works on bit patterns regardless of whatever the bits may represent at a higher level (such as for example a Java int). So you can swap any data type as long as it supports the XOR bitwise operator (and if it doesn't it's sometimes possible to cast to some type that does without actually copying anything).
Note that if you feel a need for algorithms like this in an application for performance reasons then Java probably isn't the optimal language.
Last edited by wolle; July 24th, 2018 at 12:37 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|