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.
import java.util.Scanner;
ReplyDeletepublic 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());
}
}
As usual, i forgot something in my comment :)
ReplyDeleteI 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
Wrong... a + b, a - b will be evaluated each time, so you will end up with something like:
ReplyDeleteNumbers after change are -2147483640 and 9
Solution in Groovy :)
ReplyDeletehttp://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