How to swap two integers in one line?

This question was asked during IBM’s interview in our campus in 2005:

How would you swap two integers in one statement without using a temporary variable in C/C++?

After thinking about it for some time, this is what I got (this is in Java):

class Swap
{
    public static void main( String[] args )
    {
        int a, b;
        a = 46;
        b = 47;
        System.out.println( "a = " + a + ", b = " + b );
        a = b | ( 0 & (b = a));
        System.out.println( "a = " + a + ", b = " + b );
    }
}

However, the interviewer gave a hint that it requires the use of XOR operator. If any one of you can think of a solution using XOR, please post your solution here.

Advertisements

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