Most elegant way to change 0 to 1 and vice versa

后端 未结 6 1106
眼角桃花
眼角桃花 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:27

    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
    

提交回复
热议问题