Most elegant way to change 0 to 1 and vice versa

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

    Use bit xor

    i ^= 1;

    0 讨论(0)
  • 2020-12-01 03:16
    int x = 0;
    x=(int)Math.cos(x);
    System.out.println("X value "+x);
    
    0 讨论(0)
  • 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.)

    0 讨论(0)
  • 2020-12-01 03:22

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

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-01 03:28

    subtraction?

    i = 1 - i;
    
    0 讨论(0)
提交回复
热议问题