有没有办法不使用逻辑和位运算符,只使用算术运算符,在值为0和1的整数之间切换?
如果变量为0,variable ?= variable将使变量为1; 如果为1,则使变量为0。
variable ?= variable
x = 1 - x
Will switch between 0 and 1.
int flip(int i){ return 1 - i; };
Assuming that it is initialized as a 0 or 1:
Just for a bit of variety:
x = 1 / (x + 1); x = (x == 0); x = (x != 1);
Not sure whether you consider == and != to be arithmetic operators. Probably not, and obviously although they work in C, more strongly typed languages wouldn't convert the result to integer.
==
!=
Edit: I misread the question, thought the OP could use any operator
any
A Few more...(ignore these)
x ^= 1 // bitwise operator x = !x // logical operator x = (x <= 0) // kinda the same as x != 1
Without using an operator?
int arr[] = {1,0} x = arr[x]
Yet another way:
x = (x + 1) % 2
Comedy variation on st0le's second method
x = "\1"[x]
you can simply try this
+(!0) // output:1 +(!1) // output:0
Another way to flip a bit.
x = ABS(x - 1) // the absolute of (x - 1)
You can use simple: abs(x-1) or just: int(not x)
abs(x-1)
int(not x)