+ 1

How to swap two numbers without using a third variable?

it can be done using (+,-) and(*,/).

4th Jul 2017, 8:51 PM
Imran Khan
Imran Khan - avatar
6 ответов
+ 8
a, b = b, a :D
4th Jul 2017, 9:30 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 6
You can also use the bitwise xor operator: a ^= b; b ^= a; a ^= b; // a and b are now swapped
4th Jul 2017, 9:09 PM
Squidy
Squidy - avatar
+ 4
/*swapping two numbers without temp variable. Can also replace + with * and - with / */ #include <iostream> #include<conio.h> using namespace std; int main() { int a,b; a=10; b=20; cout<<"a and b before swapping "<<a<<" "<<b<<endl; a=a+b; b=a-b; a=a-b; cout<<"a and b after swapping "<<a<<" "<<b; return 0; }
4th Jul 2017, 8:52 PM
Imran Khan
Imran Khan - avatar
5th Jul 2017, 3:48 AM
Krishna Teja Yeluripati
Krishna Teja Yeluripati - avatar
+ 1
https://code.sololearn.com/cASd5yJTSj7P/?ref=app
8th Jul 2017, 8:22 AM
Srishti Aggarwal
Srishti Aggarwal - avatar
- 1
Can try this one out Let a and be the two integers to be swapped a = a * b; b = a / b; a = a / b:
5th Jul 2017, 3:43 AM
Shubh Saxena
Shubh Saxena - avatar