Most elegant way to change 0 to 1 and vice versa

后端 未结 6 1070
眼角桃花
眼角桃花 2020-12-01 02:49

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

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-01 03:21

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

提交回复
热议问题