Reputation: 3548
I know that ^
is the xor operator in Java. But I couldn't understand it in the following context.
int step = 0;
...
step ^=1;
Source: Google Code Jam 2014 (Participant's answer)
File Link : here
Upvotes: 0
Views: 223
Reputation: 6739
it goes under assignment operator category like
+= -= *= /= %= &= ^= |= <<= >>= >>>=
means
^=
bitwise exclusive OR and assignment operator
step ^=1;
as same as step = step ^ 1;
Upvotes: 2
Reputation: 37645
As others have pointed out, step ^=1
flips the least significant bit of step
. This makes even numbers get 1 bigger, and odd numbers get 1 smaller.
Examples:
0 --> 1
1 --> 0
7 --> 6
6 --> 7
-3 --> -4
Upvotes: 1
Reputation: 626
From Java Tutorials,
^
Assume integer variable A holds 60 and variable B holds 13 then:
Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49 which is 0011 0001
In your case it is,
step = step^1
and in result you get step=1
http://www.tutorialspoint.com/java/java_basic_operators.htm
Upvotes: 1
Reputation: 37023
step ^=1
means step = step xor 1
. Similar to step += 1
which gets evaluated to step = step + 1
So ^= is short hand xor operator.
So xor table says:
operand1 operand2 output
0 0 0
0 1 1
1 0 1
1 1 0
so if my step is 1, then 1 xor 1 would be 0.
Upvotes: 1