Swap 0 and 1

Just assume that you have a flag which will store either 0 or 1. At one stage you have to check the value of the flag and swap it. i.e. if it has 0 change it to 1 and if it has 1 change it to 0. How do you do this ?


Assuming that the variable is x, in Java or C#, normally you will write it as follows.


if (x==0)





but there is a fantastic shortcut. Why don’t you write it as follows?



Why don’t you try out to use the same logic to swap any two numbers?

This entry was posted in 05. කෙටි ක්‍රම. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s