Tuesday, December 10, 2019

How To Swap 2 Integers Without Using Temporary Variable Inwards Java?

One of the oldest flim-flam interrogation from programming interview is, How create y'all swap 2 integers without using temp variable? This was start asked to me on a C, C++ interview together with and thus several times on diverse Java interviews. Beauty of this interrogation lies both on flim-flam to think near how y'all tin swap 2 numbers alongside out tertiary variable, precisely also problems associated alongside each approach. If a programmer tin think near integer overflow together with consider that inwards its solution together with thus it creates a real skillful impression inwards the oculus of interviewers. Ok, thus let's come upward to the point, suppose y'all receive got tow integers i = 10 together with j = 20, how volition y'all swap them without using whatsoever variable thus that j = 10 together with i = 20? Though this is mag occupation together with solution operate to a greater extent than or less inwards every other programming language, y'all demand to create this using Java programming constructs. You tin swap numbers past times performing some mathematical operations e.g. add-on together with subtraction together with multiplication together with division, precisely they confront occupation of integer overflow.


There is a bang-up flim-flam of swapping number using XOR bitwise operator which proves to live on ultimate solution. We volition explore together with sympathize each of these iii solutions inwards particular here, together with if y'all are hungry for to a greater extent than programming questions together with solutions, y'all tin e'er accept a await at Cracking the Coding Interview: 150 Programming Questions together with Solutions, i of the best majority to create for programming undertaking interviews.




Solution 1 - Using Addition together with Subtraction

You tin use + together with - operator inwards Java to swap 2 integers equally shown below :
a = a + b; b = a - b;   // genuinely (a + b) - (b), thus at i time b is equal to a a = a - b;   // (a + b) -(a), at i time a is equal to b

You tin come across that its genuinely prissy flim-flam together with start fourth dimension it took sometime to think near this approach. I was genuinely happy to fifty-fifty think near this solution because its neat, precisely happiness was brusque lived because interviewer said that it volition non operate 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 past times Integer.MAX_VALUE together with if subtraction is less than minimum value i.e. Integer.MIN_VALUE.

It confused me together with I conceded alone to abide by that the code is absolutely fine together with operate perfectly inwards Java, because overflows are clearly defined. Ofcourse same solution volition non operate inwards C or C++ precisely it volition operate 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 at i time Integer.MAX_VALUE together with -2147483639 - 2147483647 volition i time again overflow to laissez passer on y'all 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 operate inwards linguistic communication which doesn't grip integer overflow similar Java e.g. C together with C++. Java provides several bitwise together with bitshift operator, i of them is XOR which is denoted past times ^.

If y'all recollect XOR truth tabular array together with thus y'all know that Influenza A virus subtype H5N1 XOR B volition render 1 if Influenza A virus subtype H5N1 together with B are dissimilar together with 0 if Influenza A virus subtype H5N1 together with B are same. This holding gives nascency to next code, popularly know equally XOR trick:

x = x ^ y; y = x ^ y;   // at i time y = x x = x ^ y;  // at i time x = y

Let's come across these examples inwards activeness past times writing a elementary Java program, equally shown below.





Progarm to Swap Two Integers without tempoarry variable inwards Java 

In this Java program, I volition present y'all twain of ways to swap 2 integers without using whatsoever temporary or tertiary variable, together with what are problems comes alongside each approach together with which i volition operate inwards all conditions. Actually the 2 pop solution plant perfectly fine inwards Java precisely candidates, peculiarly those coming from C together with C++ background oftentimes think that start solution is broken together with volition neglect on integer boundaries, precisely that's non true. Integer overflows are clearly define inwards Java e.g. Integer.MAX_VALUE + 1 volition resultant inwards Integer.MIN_VALUE, which agency if y'all create both add-on together with subtraction inwards alongside same railroad train of numbers, your resultant volition live on fine, equally seen inwards higher upward 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;          // i way using arithmetics operator e.g. + or -         // won't operate 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; // genuinely (a + b) - (b), thus at i time b is equal to a         a = a - b; // (a + b) -(a), at i time 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         // past times using XOR bitwise operator         // Known equally XOR trick         System.out.println("Swap 2 integers without tertiary 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 tertiary variable using XOR bitwise Operator Before swap 'x': 30, 'y': 60 After swapping, 'x': 60, 'y': 30

That's all near how to swap 2 integers without using temporary variable inwards Java. Unlike pop belief that start solution volition non operate on integer boundaries i.e. approximately maximum together with minimum values, which is also truthful for languages similar C together with C++, it operate perfectly fine inwards Java. Why? because overflow is clearly define together with add-on together with subtraction together negate the number of overflow. There is no incertitude near minute solution equally it is the best solution together with non dependent area to whatsoever sign or overflow problem. It is also believed to live on fasted way to swap 2 numbers without using temp variable inwards Java.

together with how near this meme :)


If y'all are interested inwards solving some elementary together with some tricky programming questions, I advise y'all to accept a await at next railroad train of programming problems :
  • Top thirty Array based programming problems for Java programmers? [problems]
  • Top xx String based coding problems for Java programmers? [problems]
  • Top 10 Programming together with 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 beginning of a number inwards Java? [solution]
  • How to impress Fibonacci serial inwards Java without using recursion? [solution]

If y'all are preparing for programming undertaking interviews together with looking for some skillful resources, together with thus y'all 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 together with Solutions [see here]

Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures together with Algorithms: Deep Dive Using Java
Algorithms together with Data Structures - Part 1 together with 2

No comments:

Post a Comment