Python Programm zum Vertauschen zweier Zahlen ohne Verwendung einer dritten Variable

โšก Intelligente Zusammenfassung

Tauschping two numbers without a third variable exchanges their values in place using arithmetic addition and subtraction, the bitwise XOR operator, or bitwise-arithmetic tricks. Python can also swap directly with tuple unpacking.

  • ๐Ÿ”˜ Classic method: The usual swap holds one value in a temporary variable, which these techniques avoid.
  • โž• Arithmetic swap: Exchange values with a = a + b, then b = a โˆ’ b, then a = a โˆ’ b.
  • ๐Ÿ”€ XOR swap: Apply the bitwise XOR operator three times to swap integers with no overflow.
  • ๐Ÿงฎ Bitwise-arithmetic: Use AND, OR, and complement operators to reproduce addition and subtraction.
  • ๐Ÿ Python Abkรผrzung: Tuple unpacking, a, b = b, a, swaps any two values in one line.
  • ๐Ÿค– AI and data: Tuple swaps and NumPy indexing reorder array elements in machine learning prep.

Zwei tauschen Numbers Without Using a Third Variable

The sections below cover four ways to swap without a temporary variable, plus arithmetic overflow.

In programming languages, swapping means exchanging the values of two variables. The variable might contain a number, string, list or array, object, etc. The general way of swapping Dabei wird eine temporรคre Variable verwendet, um Werte zu speichern. Zum Beispiel:

Zwei tauschen Numbers

Die allgemeinen Schritte des Tauschsping Die beiden Zahlen lauten:

  • Declare a temporary variable C
  • Weisen Sie C den Wert von A zu, was bedeutet, dass C = A ist. Jetzt ist C = 20
  • Weisen Sie A den Wert von B zu, also A = 30
  • Weisen Sie B den Wert von C zu, also ist B = 20, da C den Wert 20 hat.

This is how swapping is done with the help of a temporary variable, and it works for both integer and float numbers.

Tauschen Sie mithilfe der arithmetischen Gleichung

Wie wir wissen, Tauschping means to interchange the content of two objects or fields or variables. Swap using an arithmetic operation means performing the swap using a mathematical equation, i.e., addition and subtraction.

If we are given two numbers and asked to swap without using a temporary variable, then using three arithmetic equations, we can swap the numbers.

Pseudocode fรผr Tauschping numbers using an arithmetic operation:

A = A + B
B = A - B
A = A - B

Let us assume we have two numbers, A = 20 and B = 30.

Bedingung 1: A = A+B

So, the current value of A is 20+30 = 50

Bedingung 2: B = AB

Nun ist B = 50-30 = 20
We can see that we got the value of A in B.

Bedingung 3: A = AB

SchlieรŸlich ist A = 50-20 = 30
A hat den Anfangswert von B.

Also haben wir einfach die Nummern vertauscht.

Here is the program to swap two numbers in C/C++:

#include<stdio.h>
int main()
{
	int a, b;
	printf("Enter value of A: ");
	scanf("%d", & a);
	printf("Enter value of B: ");
	scanf("%d", & b);
	printf("A = %d, B = %d", a, b);
	a = a + b;
	b = a - b;
	a = a - b;
	printf("\nNow, A = %d, B = %d", a, b);
}

Ausgang:

Enter value of A: 20
Enter value of B: 30
A = 20 , B = 30
Now, A = 30 , B = 20

Programm in Python:

a = int(input("Enter value of A: "))
b = int(input("Enter value of B: "))
print("A = {} and B = {}".format(a, b))
a = a + b
b = a - b
a = a - b
print("Now, A = {} and B = {}".format(a, b))

Ausgang:

Enter value of A: 20
Enter value of B: 30
A = 20 , B = 30
Now, A = 30 , B = 20

Jetzt in Python, we do not even need to perform arithmetic operations. We can use:

a,b = b,a

Here is a demonstration where a=20, b=30;

Tauschen Sie mithilfe der arithmetischen Gleichung

Tauschen mit Bitwise XOR OperaDo.

This method is also known as XOR swap. XOR means exclusive OR. We take two bits as inputs to the XOR in this bitwise operation. To get one output from XOR, only one input must be 1. Otherwise, the output will be 0. The following table shows the output for all combinations of input A and B.

We need to know how the XOR operation works to swap two numbers using the bitwise operation. Here is a table for XOR where A and B are the input values.

A B Ein XOR-B
0 0 0
0 1 1
1 0 1
1 1 0

If two inputs have the same value, then the XOR operation gives 0; otherwise, 1. For this example, we will be using a 3 XOR operation. In most programming languages, XOR is denoted as โ€œ^โ€.

Let us assume A=4 (in Binary = 0100) and B=7 (in Binary, 0111)

Bedingung 1: A = A ^ B

A 0 1 0 0
B 0 1 1 1
A ^ B 0 0 1 1

Nun ist A = 0011 (in Binรคrform).

Bedingung 2: B = A^B

A 0 0 1 1
B 0 1 1 1
A ^ B 0 1 0 0

Also B = 0100, was der anfรคngliche Binรคrwert von A war.

Bedingung 3: A = A^B

A 0 0 1 1
B 0 1 0 0
A ^ B 0 1 1 1

SchlieรŸlich ist A = 0111, was der รคquivalente Binรคrwert von B war.

Programmieren in C/C++:

#include<stdio.h>
int main()
{
	int a, b;
	printf("Enter value of A: ");
	scanf("%d", & a);
	printf("Enter value of B: ");
	scanf("%d", & b);
	printf("A = %d, B = %d", a, b);
	a = a ^ b;
	b = a ^ b;
	a = a ^ b;
	printf("\nNow, A = %d, B = %d", a, b);
}

Ausgang:

Enter value of A:4
Enter value of B:7
A=4, B=7
Now, A=7, B=4.

Programm in Python:

a = int(input("Enter value of A: "))
b = int(input("Enter value of B: "))
print("A = {} and B = {}".format(a, b))
a = a ^ b
b = a ^ b
a = a ^ b
print("Now, A = {} and B = {}".format(a, b))

Ausgang:

Enter the value of A:10
Enter the value of B:15
A=10 and B=15
Now, A=15,B=10.

Tausch Numbers mit Bitweiser Arithmetik

This method is the same as the arithmetic method, but we will use bitwise operations such as AND, OR, and complement to perform addition and subtraction. Before going to the steps, let us look over โ€œcomplementโ€ quickly.

1โ€™s complement means to change all the 0 to 1 and 1 to 0. Let us take an example.

  • Let us assume a number 23, a decimal number.
  • Converting to Binary gives us 10111. There are only 5 bits, but the computer stores numbers in 8, 16, 32, 64 โ€ฆ bits. So let us add zero in front of the Binary. It will not change the original value of the number. So it will become 00010111.
  • As we know, 1โ€™s complement means to change all the 0 to 1 and 1 to 0, so performing 1โ€™s complement over 00010111 gibt 11101000.

This 1โ€™s complement is represented with the โ€œ~โ€ symbol in most programming languages. Putting this symbol before any integer values or floating-point values will give the 1โ€™s complement.

Und 2er-Komplement bedeutet das Hinzufรผgen der binรคren โ€ž1โ€œ zum 1er-Komplement. Wenn wir das 2er-Komplement zur obigen Zahl machen:

  • Binรคr = 00010111
  • 1โ€™s complement = 11101000
  • Einerkomplement:

11101000

+ 1

11101001

Das Zweierkomplement ist also 2. Dies ist die Binรคrzahl fรผr -11101001.
Zusammenfassend sieht die Ausfรผhrung des Zweierkomplements einer Zahl A wie folgt aus:

2er-Komplement von A = (~A) + 1

Now let us assume A=8 (binary 00001000), B=10 (00001010)

Bedingung 1: A = (A & B) + (A | B)

It is equivalent to A = A + B.

A & B = 00001000 & 00001010 = 00001000

A | B = 00001000 | 00001010 = 00001010

Nun, 00001000 + 00001010 = 00010010 (Dezimal 18)

Also, A = 18

Bedingung 2: B = A + (~B) + 1

It is equivalent to B = A-B

Hier gilt B = A โ€“ B

Aus der obigen Diskussion ergibt sich, dass wir, falls wir Unteraufgaben durchfรผhren mรผssen, โ€ฆtracBei dieser Kontraktion bilden wir das Zweierkomplement der negativen Zahl und addieren sie dann.

Also -B = ~B + 1

Now, B = 00010010 + (11110101) + 1 = 00001000

Der Wert von B entspricht der Dezimalzahl 8, dem Anfangswert.

Bedingung 3: A = A + (~B) + 1

It is equivalent to A = A-B

Nun ist A = 00010010 + 11110111 + 1

A = 00001010 (entspricht Dezimalzahl 10)

SchlieรŸlich erhielt A den Wert von B. Somit ergab sich der Tausch.ping wurde abgeschlossen.

Programmieren in C/C++:

#include<stdio.h>
int main()
{
	int a, b;
	printf("Enter value of A: ");
	scanf("%d", & a);
	printf("Enter value of B: ");
	scanf("%d", & b);
	printf("A = %d, B = %d", a, b);
	a = (a & b) + (a | b);
	b = a + ~b + 1;
	a = a + ~b + 1;
	printf("\nNow, A = %d, B = %d", a, b);
}

Ausgang:

Enter the value of A: 8
Enter the value of B:10
A=8, B=10
Now, A=10, B=8

Programm in Python:

a = int(input("Enter value of A: "))
b = int(input("Enter value of B: "))
print("A = {} and B = {}".format(a, b))
a = (a & b) + (a | b)
b = a + ~b + 1
a = a + ~b + 1
print("Now, A = {} and B = {}".format(a, b))

Ausgang:

Enter the value of A: 25
Enter the value of B: 25
A = 25 and B = 25
Now, A = 25 and B = 25

Was ist ein arithmetischer รœberlauf?

The term overflow means exceeding the limit. Arithmetic overflow means that the result of any arithmetic operation exceeds the range or limit of the computer architectureโ€™s number representation. For example, if a number is divided by zero, it becomes infinite, and the computer number system cannot hold it in 32 or 64 bits.

Darstellung ganzzahliger Zahlen

Ganzzahldarstellung in einem 32-Bit-System

Die Folge des arithmetischen รœberlaufs kann sein:

  • The addition of two positive numbers becomes negative, because the sign bit might become 1, meaning a negative number.
  • The addition of two negative numbers becomes positive, because the sign bit might become 0, meaning a positive number.

Hรคufig gestellte Fragen

XOR swapping is the interview favorite: no extra memory, no overflow. Arithmetic is a fair backup, and Python developers usually just write a, b = b, a.

No. Bitwise XOR works only on integer bit patterns, not floats, doubles, or pointers. For floats, use tuple unpacking or the arithmetic swap instead.

If both variables share one memory location, XOR swapping sets the value to 0. Add an if check whenever aliasing is possible.

Yes: a = a * b, b = a / b, a = a / b. But it fails when either value is 0 and loses float precision.

Only tuple unpacking can. Writing a, b = b, a swaps strings, lists, or objects. The arithmetic and XOR tricks are integer-only.

Barely. Modern compilers already optimize temporary-variable swaps, so the trick rarely improves speed. Readable code matters more than saving one variable.

Yes. Machine learning code swaps values with Python tuple unpacking, and NumPy indexing like arr[[i, j]] = arr[[j, i]] swaps array rows in place.

Yes. GitHub Copilot and similar AI assistants produce XOR, arithmetic, and tuple-unpacking swaps from a prompt. Review each for overflow and aliasing bugs.

Fassen Sie diesen Beitrag mit folgenden Worten zusammen: