How to swap 2 Integers without using temporary variable inward Java?

One of the oldest clit a fast 1 on inquiry from programming interview is, How produce you lot swap 2 integers without using temp variable? This was get-go asked to me on a C, C++ interview as well as hence several times on diverse Java interviews. Beauty of this inquiry lies both on clit a fast 1 on to think virtually how you lot tin swap 2 numbers alongside out 3rd variable, exactly also problems associated alongside each approach. If a programmer tin think virtually integer overflow as well as consider that inwards its solution hence it creates a really adept impression inwards the oculus of interviewers. Ok, hence let's come upwards to the point, suppose you lot lead keep tow integers i = 10 as well as j = 20, how volition you lot swap them without using whatever variable hence that j = 10 as well as i = 20? Though this is periodical employment as well as solution move to a greater extent than or less inwards every other programming language, you lot demand to produce this using Java programming constructs. You tin swap numbers yesteryear performing some mathematical operations e.g. add-on as well as subtraction as well as multiplication as well as division, exactly they human face upwards employment of integer overflow.


There is a keen clit a fast 1 on of swapping divulge using XOR bitwise operator which proves to live on ultimate solution. We volition explore as well as empathise each of these 3 solutions inwards particular here, as well as if you lot are hungry for to a greater extent than programming questions as well as solutions, you lot tin ever accept a await at Cracking the Coding Interview: 150 Programming Questions as well as Solutions, 1 of the best majority to cook for programming undertaking interviews.




Solution 1 - Using Addition as well as Subtraction

You tin use + as well as - operator inwards Java to swap 2 integers equally shown below :
a = a + b; b = a - b;   // truly (a + b) - (b), hence straight off b is equal to a a = a - b;   // (a + b) -(a), straight off a is equal to b

You tin come across that its truly overnice clit a fast 1 on as well as get-go fourth dimension it took sometime to think virtually this approach. I was truly happy to fifty-fifty think virtually this solution because its neat, exactly happiness was brusk lived because interviewer said that it volition non move inwards all conditions. He said that integer volition overflow if add-on is to a greater extent than than maximum value of int primitive equally defined yesteryear Integer.MAX_VALUE as well as if subtraction is less than minimum value i.e. Integer.MIN_VALUE.

It confused me as well as I conceded exclusively to abide by that the code is absolutely fine as well as move perfectly inwards Java, because overflows are clearly defined. Ofcourse same solution volition non move inwards C or C++ exactly it volition move absolutely fine inwards Java. Don't believe me? hither is the proof :

a = Integer.MAX_VALUE; b = 10;  System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);  a = (a + b) - (b = a);  System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);  Output : Before swap 'a': 2147483647, 'b': 10  After swapping, 'a': 10, 'b': 2147483647 

Here add-on of 2 numbers volition overflow, Integer.MAX_VALUE + 10 = -2147483639, but nosotros are also doing subtraction, which volition compensate this value, because b is straight off Integer.MAX_VALUE as well as -2147483639 - 2147483647 volition over again overflow to give you lot 10 equally output.


Solution 2 - Using XOR trick

Second solution to swap 2 integer numbers inwards Java without using temp variable is widely recognized equally the best solution, equally it volition also move inwards linguistic communication which doesn't handgrip integer overflow similar Java e.g. C as well as C++. Java provides several bitwise as well as bitshift operator, 1 of them is XOR which is denoted yesteryear ^.

If you lot recollect XOR truth tabular array hence you lot know that Influenza A virus subtype H5N1 XOR B volition render 1 if Influenza A virus subtype H5N1 as well as B are dissimilar as well as 0 if Influenza A virus subtype H5N1 as well as B are same. This belongings gives nativity to next code, popularly know equally XOR trick:

x = x ^ y; y = x ^ y;   // straight off y = x x = x ^ y;  // straight off x = y

Let's come across these examples inwards activeness yesteryear writing a unproblematic Java program, equally shown below.





Progarm to Swap Two Integers without tempoarry variable inwards Java 

In this Java program, I volition exhibit you lot duet of ways to swap 2 integers without using whatever temporary or 3rd variable, as well as what are problems comes alongside each approach as well as which 1 volition move inwards all conditions. Actually the 2 pop solution industrial plant perfectly fine inwards Java exactly candidates, specially those coming from C as well as C++ background oftentimes think that get-go solution is broken as well as volition neglect on integer boundaries, exactly that's non true. Integer overflows are clearly define inwards Java e.g. Integer.MAX_VALUE + 1 volition final result inwards Integer.MIN_VALUE, which way if you lot produce both add-on as well as subtraction inwards alongside same ready of numbers, your final result volition live on fine, equally seen inwards in a higher house example.

/** * Java programme to swap 2 integers without using temp variable * * @author java67 */ public class Problem {      public static void main(String args[]) {         int a = 10;         int b = 20;          // 1 way using arithmetics operator e.g. + or -         // won't move if amount overflows         System.out.println("One way to swap 2 numbers without temp variable");         System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);         a = a + b;         b = a - b; // truly (a + b) - (b), hence straight off b is equal to a         a = a - b; // (a + b) -(a), straight off a is equal to b          System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);          // some other example         a = Integer.MIN_VALUE;         b = Integer.MAX_VALUE;          System.out.printf("Before swap 'a': %d, 'b': %d %n", a, b);          a = (a + b) - (b = a);          System.out.printf("After swapping, 'a': %d, 'b': %d %n", a, b);          // Another way to swap integers without using temp variable is         // yesteryear using XOR bitwise operator         // Known equally XOR trick         System.out.println("Swap 2 integers without 3rd variable                              using XOR bitwise Operator");          int x = 30;         int y = 60;          System.out.printf("Before swap 'x': %d, 'y': %d %n", x, y);         x = x ^ y;         y = x ^ y;         x = x ^ y;          System.out.printf("After swapping, 'x': %d, 'y': %d %n", x, y);     }  }  Output One way to swap 2 numbers without temp variable Before swap 'a': 10, 'b': 20 After swapping, 'a': 20, 'b': 10 Before swap 'a': -2147483648, 'b': 2147483647 After swapping, 'a': 2147483647, 'b': -2147483648 Swap 2 integers without 3rd variable using XOR bitwise Operator Before swap 'x': 30, 'y': 60 After swapping, 'x': 60, 'y': 30

That's all virtually how to swap 2 integers without using temporary variable inwards Java. Unlike pop belief that get-go solution volition non move on integer boundaries i.e. around maximum as well as minimum values, which is also truthful for languages similar C as well as C++, it move perfectly fine inwards Java. Why? because overflow is clearly define as well as add-on as well as subtraction together negate the final result of overflow. There is no incertitude virtually mo solution equally it is the best solution as well as non dependent champaign to whatever sign or overflow problem. It is also believed to live on fasted way to swap 2 numbers without using temp variable inwards Java.

as well as how virtually this meme :)


If you lot are interested inwards solving some unproblematic as well as some tricky programming questions, I propose you lot to accept a await at next ready of programming problems :
  • Top thirty Array based programming problems for Java programmers? [problems]
  • Top twenty String based coding problems for Java programmers? [problems]
  • Top 10 Programming as well as Coding exercises for Java programmers? [problems]
  • How to abide by overstep 2 numbers from integer array? [solution]
  • How to abide by duplicate characters inwards Java String? [solution]
  • How to abide by foursquare source of a divulge inwards Java? [solution]
  • How to impress Fibonacci serial inwards Java without using recursion? [solution]

If you lot are preparing for programming undertaking interviews as well as looking for some adept resources, hence you lot tin also accept aid from next books, 2 of the best resources of programming questions :
  • Programming Interviews Exposed: Secrets to Landing Your Next Job [see here]
  • Cracking the Coding Interview: 150 Programming Questions as well as Solutions [see here]

Subscribe to receive free email updates:

0 Response to "How to swap 2 Integers without using temporary variable inward Java?"

Posting Komentar