+ 2
a^=b?
In a challenge question, two variables a and b were passed by reference and they were made to undergo this operation : a^=b; b^=a; a^=b; What does this do?
15 Answers
+ 2
ooh i puzzeled it with smthing else..
^ is binary XOR OPERATOR
a^b=40
it means 00101000
binary of 40 is 101000
It copies the bit if it is set inone operand but not both.
+ 2
a=2 (010); b=6 (110) //(binary)
a^=b; //a=a^b -- 010 xor 110 = 100 a
b^=a; //b=b^a -- 110 xor 100 = 010 b
a^=b; //a=a^b -- 100 xor 010 = 110 a
now: a=6 (110) and b=2 (010)
interchanged values
note: this could be a quiz on JavaScript, who votes up ๐
+ 1
It swops the values of a&b
+ 1
No it doesn't. I have seen the swapping code, it uses a third variable, else we add the numbers in beginning when swapping by two variables :/ I don't think that's the right answer.
+ 1
It does swop I checked
+ 1
You don't need a third variable you need manipulation
+ 1
@sayan bro, i know we can swap using only two variables. I added that in my response. Thanks though :)
@Vengat, yea i guess it swaps. I tried it too. Is there a name for this operator? I'll just learn more about it online :)
+ 1
Ohhh... Well then I guess that much info should do. I'll search it up man. Thanks
0
I mean, your code swops the variables
0
I dunno, it is a bitwise operator all I care
0
It's okay.
*yawns* good night
0
### BUT IT IS A SWAPPING METHOD###
BINARY SWAPPING
WITHOUT THIRD VARIABLE
0
&
|
^
<<
>>
~
6 in total bitwise operator...
- 1
u can swap without using a third variable brother...
##
@ siraz
- 1
a=5
b=6
a=a+b
b=a-b
a=a-b
swapping