Sunday, May 10, 2009

Puzzle 22 – Solution

This is a pretty classic puzzle with a pretty classic solution. The program below swaps two numbers without using a temporary variable.

package com.twister;
import java.util.Scanner;

public class Swap{

public static void swap(int a,int b){
System.out.println(
"Numbers before change are "
+ a + " and " + b);
a
= a + b;
b
= a - b;
a
= a - b;
System.out.println(
"Numbers after change are "
+ a + " and " + b);
}

public static void main(String args[]){
swap(
new Scanner(System.in).nextInt(),
new Scanner(System.in).nextInt());
}
}

This program works for all values of integer even if we overflow them. Don’t believe me – go ahead and give it a try!!

Congrats to
1. Behive
for getting the right solution.

No comments:

Post a Comment

Solution for this question?