Wednesday, May 6, 2009

Puzzle 22 - Swap again!

Language – Java/C++ | Type – Problem (Code) | Last date 10-May-2009 12:00 p.m. IST | Points 5

This is one of those classic puzzles …

Write a program that swaps two numbers.
Twist: Do not use a temporary variable while doing the swap.

Think this one is pretty easy? You might want to try out its tougher variation here.

Got an answer? Why don’t you leave it here.

2 comments:

  1. int a = 4;
    int b = 5;

    a = a + b; // a = 4 + 5 = 9
    b = a - b; // b = 9 - 5 = 4 -> one down, one to go
    a = a - b; // a = 9 - 4 = 5 -> done.

    ReplyDelete
  2. 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());
    }
    }

    PS: i think i answered previously, but my browser broke, so i'm not sure if this is a double post or not.. besides, i only provided the math on my previous answer.. this one should probably run, as it has the class definition and methods :)

    ReplyDelete

Solution for this question?