jeudi 13 août 2015

How to swap two Integers without using temporary variable in Java?

One of the oldest trick question from programming interview is, How do you swap two integers without using temp variable? This was first asked to me on a C, C++ interview and then several times on various Java interviews. Beauty of this question lies both on trick to think about how you can swap two numbers with out third variable, but also problems associated with each approach. If a programmer can think about integer overflow and consider that in its solution then it creates a very good impression in the eye of interviewers. Ok, so let's come to the point, suppose you have tow integers i = 10 and j = 20, how will you swap them without using any variable so that j = 10 and i = 20? Though this is journal problem and solution work more or less in every other programming language, you need to do this using Java programming constructs. You can swap numbers by performing some mathematical operations e.g. addition and subtraction and multiplication and division, but they face problem of integer overflow.
Read more »
Share:

0 commentaires:

Enregistrer un commentaire