+ 2
Hi, who can help me to solve this
var a=x; var b =y; when write alert(a) it will be y, and alert(b) to be x: without use any functions, cicle, if, other var
14 Respuestas
+ 5
So you want to swap two variables without using a third one?
Hint: if we do a += b, then a is x+y and b is y. What can we do now to turn b into x? 😉 The rest is similar.
+ 2
1) [a,b]=[b,a];
2) b = [a, a = b][0];
3) b^=a^=b, a^=b;
+ 1
thank you
+ 1
You're welcome. Were you able to solve it? Let me know if what I said sounds confusing :)
+ 1
ok, if i need ask you, i will
+ 1
a += b; // now a is x+y, b is y
b = a - b; // now a is x+y, b is x
a -= b; // now a is y, b is x
Done! Does that makes sense?
+ 1
Kishalaya Saha, if x can be used, the swapping process is significantly easier:
a=b; b=x;
The task is not to use anything except a and b
+ 1
Микола Федосєєв Thanks, I was careless. Fixed.
+ 1
a=x
b=y
// swap using math
a-=b // a=x-y
b+=a // b=x
a=b-a // a=y
// swap using xor
a^=b // a=x^y
b^=a // b=y^(x^y)=x
a^=b // a=(x^y)^x=y
+ 1
Yes, I'm aware of the bitwise XOR swap. But I don't think it's easier to understand than the add-subtract method.
0
i try to do it just now, thank you once more
0
Friend i can't solve this, i am beginner and i don't know what to do. Help
0
thank you friend, but i dont understand, i am beginner, i need very simillar answer
0
Let's reader decide what's better. If he/she is not familiar with xor, at least the fact of such possibility should be put into brains. Understanding will come later. Add-substract may be not too easy for big numbers with it's overflow problem, while xor is absolutely clean.