Adblock breaks this site

Java Problem/Puzzle

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

  1. Pottworth

    Pottworth Member

    Joined:
    Nov 27, 2005
    Posts:
    83
    Referrals:
    0
    Sythe Gold:
    0
    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.
     
  2. blindkilla

    blindkilla Guru
    $25 USD Donor New

    Joined:
    Jun 22, 2005
    Posts:
    1,896
    Referrals:
    0
    Sythe Gold:
    6
    Discord Unique ID:
    282000633404456960
    Discord Username:
    sogord
    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;
    
     
  3. Nullware

    Nullware Guru

    Joined:
    Jan 30, 2007
    Posts:
    1,761
    Referrals:
    4
    Sythe Gold:
    0
    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
     
  4. Pottworth

    Pottworth Member

    Joined:
    Nov 27, 2005
    Posts:
    83
    Referrals:
    0
    Sythe Gold:
    0
    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] >


 
 
Adblock breaks this site