Is there a way without using 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.
Is there a way without using 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.
x
is in a specific range of positive numbers, then you can also use this to reverse its value (ie. 7-x
= 0/7, 1/6, 2/5, 3/4).
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]
x = !x
is a good solution because it copes with values that aren't zero or one.
Oct 28, 2015 at 9:23
Yet another way:
x = (x + 1) % 2
x = (A + B) % 2
if A and B are both 0 or 1. Thanks!
Comedy variation on st0le's second method
x = "\1"[x]
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
!x
,(x <= 0)
,(x == 0)
, etc.