Convert 0 to 1 and 1 to 0 in Java

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.

Using XOR

You can use xor operator with 1 to convert 0 to 1 and 1 to 0 in Java.

Using ternary operator

You can use ternary operator as below:

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.

Using array

If you are not looking for mathematical solution, then you can use array to swap 0 and 1 in java.

That’s all about how to convert 0 to 1 and 1 to 0 in Java.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *