CSInterviewing
Problems
Register
Login
Problems
Register
Login
menu
Swap Variables Without Temp
bitmanipulation
math
# Swap Variables Without Temp ## Difficulty Easy ## Tags `bit manipulation`, `math` ## Problem Statement Write a function that swaps the values of two integers without using a temporary variable. ## Constraints - Inputs are integers. - Do not use any additional variables for storage. ## Signatures ### Python ```python def swap(x: int, y: int) -> Tuple[int, int]: pass ``` ### Java ```java public class Solution { public Object swap(int x, int y) { return null; } } ``` ### Csharp ```csharp public class Solution { public Object swap(int x, int y) { throw new NotImplementedException(); } } ``` ### Cpp ```cpp class Solution { public: Object swap(int x, int y) { } }; ``` ### C ```c Object swap(int x, int y) { } ``` ### Ruby ```ruby def swap(x, y) end ``` ### Perl ```perl sub swap { my ($self, @args) = @_; } ``` ### Scala ```scala object Solution { def swap(x: Int, y: Int): Object = { } } ``` ### Haskell ```haskell swap :: ... -> ... swap args = undefined ``` ### Clojure ```clojure (defn swap [x y] ) ``` ### Scheme ```scheme (define (swap x y) ) ``` ## Examples ### Example 1 **Input:** ``` x = 5 y = 10 ``` **Output:** ``` (10, 5) ``` ### Example 2 **Input:** ``` x = -3 y = 7 ``` **Output:** ``` (7, -3) ``` ### Example 3 **Input:** ``` x = 0 y = 0 ``` **Output:** ``` (0, 0) ``` ## Hints ### Method 1: XOR ```python x = x ^ y y = x ^ y # Now y = original x x = x ^ y # Now x = original y ``` Uses the property: `a ^ a = 0` and `a ^ 0 = a` ### Method 2: Arithmetic ```python x = x + y y = x - y # Now y = original x x = x - y # Now x = original y ``` ⚠️ Be careful of integer overflow in languages with fixed-size integers. ### Python Note In Python, you can simply do `x, y = y, x` which is the idiomatic way.
Login required
Please log in to view the solution editor and submit code.
Login
Register