Java 将 0 更改为 1,反之亦然的最优雅方式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2411023/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 07:14:38  来源:igfitidea点击:

Most elegant way to change 0 to 1 and vice versa

javaalgorithm

提问by Roman

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 ican have only 1 or 0 value.

您可以假设i只能有 1 或 0 值。

采纳答案by Yuval Adam

i ^= 1;

i ^= 1;

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

将值与 1 进行异或。这为您提供了两种方式(以防您需要翻转0 <--> 1任一方式):

0 ^ 1 = 1
1 ^ 1 = 0

回答by Jimmy

subtraction?

减法?

i = 1 - i;

回答by Chinmay Kanchi

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

i = (i == 0)?1:0是一种方式,尽管我更喜欢 @Jimmy 和 @Yuval 的版本。

回答by doc

Use bit xor

使用位异或

i ^= 1;

i ^= 1;

回答by Larry

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

i = ( i + 1 ) % 2,虽然我认为我们都同意减法或异或方法更好!(虽然它具有“翻转开关”的额外好处,而不是二进制。)

回答by kirans346

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