Table of Contents
In this post, we wil see how to convert 0 to 1 and 1 to 0 in java.
There are lots of ways to convert 0 to 1 and 1 to 0 in Java. Let’s go through them.
Using Subtraction
This is one of easiest solution to swap 0 to 1 and vice versa. Just subtract i from 1
and assign it back to i.
1 2 3 |
i = 1-i; |
Using XOR
You can use xor operator with 1 to convert 0 to 1 and 1 to 0 in Java.
1 2 3 |
i ^=1 ; |
Using ternary operator
You can use ternary operator as below:
1 2 3 |
i = (i == 1)?0:1; |
Using addition and remainder operator
This is not better solution than subtraction or XOR.
You can add 1
to i and use % operator to find remainder and assign it back to i.
1 2 3 |
i = ( i + 1 ) % 2 |
Using array
If you are not looking for mathematical solution, then you can use array to swap 0 and 1 in java.
1 2 3 4 |
int[] arr = { 1, 0 }; i = arr [i]; |
That’s all about how to convert 0 to 1 and 1 to 0 in Java.