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
Most elegant way to change 0 to 1 and vice versa
提问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 i
can have only 1 or 0 value.
您可以假设i
只能有 1 或 0 值。
采纳答案by Yuval Adam
回答by Jimmy
subtraction?
减法?
i = 1 - i;
回答by Chinmay Kanchi
i = (i == 0)?1:0
is 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);