Wednesday, March 4, 2009

Puzzle 4 – The Swap

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

Swapping can be easy, but this is the hardest swap ever!

Write a program that swaps two numbers.
Twist: Do not use “=” (equal sign) in entire program.

(Hard isn't it? )

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

4 comments:

  1. 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);

    while(a < a + b)
    a++;
    while(b > a - b)
    b--;
    while(a > a - b)
    a--;

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

    ReplyDelete
  2. As usual, i forgot something in my comment :)

    I know the due date for this problem was allready over when i posted my solution, but i thought i'd leave my answer here anyway :)

    cheers

    ReplyDelete
  3. Wrong... a + b, a - b will be evaluated each time, so you will end up with something like:

    Numbers after change are -2147483640 and 9

    ReplyDelete
  4. Solution in Groovy :)
    http://groovyconsole.appspot.com/script/67002

    a = 123
    b = 456

    a.times{b++} //b = b + a
    b.times{a--} //a = -b
    (-a).times{b--} //b = a
    (-a*2).times{a++} //a = b

    println a
    println b

    ReplyDelete

Solution for this question?