Can You Use Arithmetic Operators to Flip Between 0 and 1

Algorithm

Algorithm Problem Overview


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.

Algorithm Solutions


Solution 1 - Algorithm

x = 1 - x

Will switch between 0 and 1.

Solution 2 - Algorithm

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]

Solution 3 - Algorithm

Yet another way:

x = (x + 1) % 2

Solution 4 - Algorithm

Assuming that it is initialized as a 0 or 1:

x = 1 - x

Solution 5 - Algorithm

Comedy variation on st0le's second method

x = "\1"[x]

Solution 6 - Algorithm

Another way to flip a bit.

x = ABS(x - 1) // the absolute of (x - 1)

Solution 7 - Algorithm

int flip(int i){
    return 1 - i;
};

Solution 8 - Algorithm

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.

Solution 9 - Algorithm

you can simply try this

+(!0) // output:1

+(!1) // output:0

Solution 10 - Algorithm

You can use simple: abs(x-1) or just: int(not x)

Solution 11 - Algorithm

yet another variation of may others that I was surprised wasn't here - (x-1)*-1

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDaniel SopelView Question on Stackoverflow
Solution 1 - AlgorithmReverend GonzoView Answer on Stackoverflow
Solution 2 - Algorithmst0leView Answer on Stackoverflow
Solution 3 - AlgorithmMAKView Answer on Stackoverflow
Solution 4 - AlgorithmHamishView Answer on Stackoverflow
Solution 5 - AlgorithmBlastfurnaceView Answer on Stackoverflow
Solution 6 - AlgorithmstomyView Answer on Stackoverflow
Solution 7 - AlgorithmruslikView Answer on Stackoverflow
Solution 8 - AlgorithmSteve JessopView Answer on Stackoverflow
Solution 9 - AlgorithmVIJAY PView Answer on Stackoverflow
Solution 10 - AlgorithmJuice1758View Answer on Stackoverflow
Solution 11 - AlgorithmReed ThorngagView Answer on Stackoverflow