Change a value from 0->1 or 1->0 with only mathematic operations
-
19-02-2021 - |
Question
I have a variable on javascrit, initialized at 0. What I'd like to do is this :
- if the value is 0, change it to 1;
- if the value is 1, change it to 0;
and I'll avoid conditional statement (like if/else) to check what the value is.
I think I just do it with some matematic operation; I thought to a NOT operation, but I don't know how to do that operation without
Solution
x = 1-x;
OTHER TIPS
you can use xor operator:
x = x XOR 1;
Short XOR syntax:
x ^= 1
Swaps 0 to 1 and 1 to 0.
Here is another notation, it also changes true, false to 1, 0.
x = +x;
If you want to switch the value
x = +!x;
If the variable is let's say i
i = 1 - i, should do the trick
if i = 0, 1 - 0 = 1 than i = 1
if i = 1, 1 - 1 = 0 than i = 0
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow