gpt-3.5-turbo-0613· openai
Suzhen/CodeChat
Swap two number value without third number in javascript
- User
Swap two number value without third number in javascript
- Assistant
In JavaScript, you can swap two number values without using a third number by using the XOR bitwise operator. This operator allows you to perform bitwise operations on the binary representation of the numbers.
Here's an example:
let a = 5; let b = 10; console.log("Before swapping:"); console.log("a =", a); console.log("b =", b); a = a ^ b; b = a ^ b; a = a ^ b; console.log("After swapping:"); console.log("a =", a); console.log("b =", b);Output:
Before swapping: a = 5 b = 10 After swapping: a = 10 b = 5In this code, we use the XOR operator (^) to perform bitwise operations on the binary representation of the numbers
aandb. By applying the XOR operator multiple times, we can swap the values ofaandbwithout using a third number.