×

# Swapping integers in one line

 1 Is there any trick to sort the integers in just a line? asked 12 Jan, 15:06 0★drp48603 25●2 accept rate: 0%

 3 There are many ways to swap the integers. But the simplest one is mentioned below. Simple Method: x = x + y - (y = x);  bit twiddling method(there might be unexpected behavior in some cases!: if (a != b) { a ^= b ^= a ^= b; \\same as a=(b=(a=b^a)^b)^a }  Other methods: a += b -= a = b-a; a /= b = (a = a*b) /b;  answered 12 Jan, 15:14 215●8 accept rate: 11%
 1 x = x + y - (y = x); is the best. But it is compiler dependent. answered 17 Jan, 21:22 26●2 accept rate: 100% True(Y). But it works in c++. (17 Jan, 21:24)
 1 Two swap two integer a and b are in python a,b=b,a answered 17 Jan, 22:58 11 accept rate: 0%
 0 @drp48603 You can use predefined swap function in c++ by including algorithm library. For swapping two variables a and b, it can be simply used as std::swap(a,b). For more details you can see here. answered 12 Jan, 15:20 4★srd091 1.4k●1●11 accept rate: 40%
 0 To swap two integers you can use a temporary varible in c++ swap(a,b) t = a ; a = b ; b = t ; answered 17 Jan, 23:59 1 accept rate: 0%
 toggle preview community wiki
Preview

By Email:

Markdown Basics

• *italic* or _italic_
• **bold** or __bold__
• image?![alt text](/path/img.jpg "title")
• numbered list: 1. Foo 2. Bar
• to add a line break simply add two spaces to where you would like the new line to be.
• basic HTML tags are also supported
• mathemetical formulas in Latex between \$ symbol

Tags:

×5
×5