You are not logged in. Please login at www.codechef.com to post your questions!

×

Swapping integers in one line

Is there any trick to sort the integers in just a line?

asked 12 Jan, 15:06

drp48603's gravatar image

0★drp48603
252
accept rate: 0%


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;
link

answered 12 Jan, 15:14

pratik_gadhiya's gravatar image

3★pratik_gadhiya
2158
accept rate: 11%

edited 12 Jan, 17:15

x = x + y - (y = x); is the best. But it is compiler dependent.

link

answered 17 Jan, 21:22

yashesh_123's gravatar image

2★yashesh_123
262
accept rate: 100%

True(Y). But it works in c++.

(17 Jan, 21:24) pratik_gadhiya3★

Two swap two integer a and b are in python a,b=b,a

link

answered 17 Jan, 22:58

kowshikdu's gravatar image

0★kowshikdu
11
accept rate: 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.

link

answered 12 Jan, 15:20

srd091's gravatar image

4★srd091
1.4k111
accept rate: 40%

To swap two integers you can use a temporary varible in c++ swap(a,b) t = a ; a = b ; b = t ;

link

answered 17 Jan, 23:59

shubhamaggarw's gravatar image

1★shubhamaggarw
1
accept rate: 0%

toggle preview
Preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • 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

Asked: 12 Jan, 15:06

Seen: 464 times

Last updated: 17 Jan, 23:59