Java Problem/Puzzle

Discussion in 'Programming General' started by Pottworth, Sep 25, 2011.

Java Problem/Puzzle
  1. Unread #1 - Sep 25, 2011 at 1:25 PM
  2. Pottworth
    Joined:
    Nov 27, 2005
    Posts:
    83
    Referrals:
    0
    Sythe Gold:
    0

    Pottworth Member

    Java Problem/Puzzle

    Okay, so I was in a lecture last week, and my teacher was talking about a question she got asked on the spot in a job interview. It's been bugging me ever since. It was something along the lines of;

    Say you had two integer variables. How would you switch the values WITHOUT creating a temporary variable?

    Can anyone figure out the solution? It's got something to do with arithmetic I believe.
     
  3. Unread #2 - Sep 25, 2011 at 1:43 PM
  4. blindkilla
    Joined:
    Jun 22, 2005
    Posts:
    1,896
    Referrals:
    0
    Sythe Gold:
    6
    Discord Unique ID:
    282000633404456960
    Discord Username:
    sogord

    blindkilla Guru
    $25 USD Donor New

    Java Problem/Puzzle

    You're right about it being arithmetic. You can do something like this.

    Code:
    [FONT=monospace]
    [/FONT]variableOne = [FONT=monospace][/FONT]variableOne + variableTwo;[FONT=monospace]
    [/FONT]variableTwo = [FONT=monospace][/FONT]variableOne - variableTwo;
    [FONT=monospace][/FONT]variableOne = [FONT=monospace][/FONT]variableOne [FONT=monospace]-[/FONT] variableTwo;
    
     
  5. Unread #3 - Sep 25, 2011 at 4:05 PM
  6. Nullware
    Joined:
    Jan 30, 2007
    Posts:
    1,761
    Referrals:
    4
    Sythe Gold:
    0

    Nullware Guru

    Java Problem/Puzzle

    XOR is usually used for swapping without a temporary variable rather than addition/subtraction because it's a far less expensive operation and can be used on a wider variety of datatypes.

    If you're really curious: http://en.wikipedia.org/wiki/XOR_swap_algorithm
     
  7. Unread #4 - Sep 29, 2011 at 5:48 PM
  8. Pottworth
    Joined:
    Nov 27, 2005
    Posts:
    83
    Referrals:
    0
    Sythe Gold:
    0

    Pottworth Member

    Java Problem/Puzzle

    Thanks for the replies! I'm kicking myself I didn't figure out the first method. I'd have never guessed the second.
     
< My RS Loader | [JQ|JS|CSS|HTML] Website Design Service [HTML|CSS|JS|JQ] >

Users viewing this thread
1 guest


 
 
Adblock breaks this site