Most elegant way to change 0 to 1 and vice versa

JavaAlgorithm

Java Problem Overview


What is the most elegant way to do the next stuff:

int i = oneOrZero;

if (i == 0) {
   i = 1;
} else {
   i = 0;
}

You can assume that i can have only 1 or 0 value.

Java Solutions


Solution 1 - Java

i ^= 1;

XOR the value with 1. This gives you both ways (in case you need to flip 0 <--> 1 either way):

0 ^ 1 = 1
1 ^ 1 = 0

Solution 2 - Java

subtraction?

i = 1 - i;

Solution 3 - Java

i = (i == 0)?1:0 is one way, though I like @Jimmy's and @Yuval's versions better.

Solution 4 - Java

i = ( i + 1 ) % 2, though I think we all agree the subtraction or xor method is better! (Though it has the added benefit of "flipping the switch" for more than binary.)

Solution 5 - Java

Use Bitwise XOR operator:

i ^= 1;

Solution 6 - Java

int x = 0;
x=(int)Math.cos(x);
System.out.println("X value "+x);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRomanView Question on Stackoverflow
Solution 1 - JavaYuval AdamView Answer on Stackoverflow
Solution 2 - JavaJimmyView Answer on Stackoverflow
Solution 3 - JavaChinmay KanchiView Answer on Stackoverflow
Solution 4 - JavaLarryView Answer on Stackoverflow
Solution 5 - JavamipView Answer on Stackoverflow
Solution 6 - Javakirans346View Answer on Stackoverflow