Can You Use Arithmetic Operators to Flip Between 0 and 1
Is there a way without usin开发者_运维问答g logic and bitwise operators, just arithmetic operators, to flip between integers with the value 0 and 1?
ie.
variable ?= variable
will make the variable 1 if it 0 or 0 if it is 1.
x = 1 - x
Will switch between 0 and 1.
Edit: I misread the question, thought the OP could use any
operator
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
Assuming that it is initialized as a 0 or 1:
x = 1 - x
Comedy variation on st0le's second method
x = "\1"[x]
Another way to flip a bit.
x = ABS(x - 1) // the absolute of (x - 1)
int flip(int i){
return 1 - i;
};
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.
you can simply try this
+(!0) // output:1
+(!1) // output:0
You can use simple:
abs(x-1)
or just:
int(not x)
精彩评论