PuzzlersWorld.com

  • Hacker Puzzle
  • Interview Puzzles
  • Number Puzzles
  • Maths Puzzles

Swap two integer variables

(No Ratings Yet)

November 3, 2012 by asinghal Leave a Comment

How to swap two integer variables without using the third variable ?
See Solution: Swap two integer variablesHide Solution

I know three solutions, comment if you know more 🙂

Solution 1:

x = x+y;
y  = x-y;
x  = x-y;

Solution 2:

y = 2*((x+y)/2) – (x =y);

Solution 3:

x = x^y;
y = x^y;
x = x^y;

Note: However solution 1 & 2 has problem of overflow doing addition of two integers might overflow. But solution 3 will not have any such problem

  • Share on Whatsapp
  • Share on Facebook
  • Share on Twitter
Facebook Comments
Next Puzzle
Find middle element of linked list

Checkout more Interview Questions Tags: Easy, Interview, Solved Puzzles

Leave a Comment Cancel reply

Submit your Puzzle

You may also like

  • Magic Trick Solution – Google Code Jam 2014
  • Lawnmower Solution: Google codejam 2013 Qual Round
  • Find a pythagorean triplet from an array
  • Find middle element of linked list
  • implement isPalindrome(int n)
  • Objective Questions set C/C++ – Part 6
  • Three blue and two red hats puzzle
  • Falling Diamonds Solution: Google codejam 2013 Round 1B
  • Manage Your Energey Solution: Google codejam 2013 Round 1A
  • Output of the recursive program

Categories

  • Aive hi Puzzles
  • Akbar and Birbal
  • Alphabetical Puzzles
  • Bollywood Puzzles
  • Google Code jam
  • Hindi Riddles
  • Interview Puzzles
  • Interview Questions
  • Logical Puzzles
  • Malayalam Puzzles
  • Maths Puzzles
  • Miscellaneous
  • Number Puzzles
  • Picture Puzzles
  • Riddles
  • Tamil Puzzles
  • Technical

Social

  • View puzzlersworld’s profile on Twitter
privacy policy

Copyright © 2025 · eleven40 Pro Theme on Genesis Framework · WordPress · Log in

  • Hacker Puzzle
  • Logo Puzzles
  • Optical Illusions
  • WhatsApp Puzzles
  • Picture Puzzles
  • Riddles
    â–¼
    • Hindi Riddles
  • Bollywood Puzzles
  • Alphabetical Puzzles
  • Aive hi Puzzles
  • Interview Puzzles
  • Logical Puzzles
  • Interview Questions
    â–²
    • Data Structures
    • Binary Tree
    • Algorithms
    • Recursion Questions
    • Amazon Interview Questions
    • Snapdeal Interview Questions
    • Google Code jam
  • Technical
  • Akbar and Birbal
  • Number Puzzles
  • Maths Puzzles
  • Miscellaneous