Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most elegant way to change 0 to 1 and vice versa

Tags:

java

algorithm

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.

like image 789
Roman Avatar asked Mar 09 '10 17:03

Roman


People also ask

Which operator changes the binary digit 0 to 1 and vice versa?

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.)


1 Answers

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 
like image 148
Yuval Adam Avatar answered Oct 19 '22 23:10

Yuval Adam