Computer Science, asked by anindyaadhikari13, 1 month ago

Tell me the Logic to swap two numbers using bitwise operator?​


RockingStarPratheek: I tried this in Python and this was my approach :

num1 = input('Enter First Number: ')
num2 = input('Enter Second Number: ')

print("\nValue of num1 before swapping: ", num1)
print("Value of num2 before swapping: ", num2)

# swapping two numbers using temporary variable
temp = num1
num1 = num2
num2 = temp

print("\nValue of num1 after swapping: ", num1)
print("Value of num2 after swapping: ", num2)

# Designed by @RockingStarPratheek
SujalSirimilla: Yes, this might work but the questionnaire asked us to use bitwise operators.
anindyaadhikari13: @RockingStarPratheek, this is an easy approach, but use bitwise operator to solve this question.
SujalSirimilla: Also, @anindyaadhikari13, I did not quite understand what you meant by your comment - "Show workings and how the result came" . Could you please specify what I should do ^^" ?
anindyaadhikari13: You can also swap without using third variable - num1, num2=num2, num1
anindyaadhikari13: I meant to say dry run.
SujalSirimilla: Okay, may be my comment was not noticed, @anindyaadhikari13 - I did not quite understand what you meant by your comment - "Show workings and how the result came" . Could you please specify what I should do ^^" ?
anindyaadhikari13: i meant to say that write the co de with dry run.

Answers

Answered by bivaspanda88
1

Answer:

Java Program to Swap Two Numbers Using Bitwise Operator

Find the binary equivalent of given variables, say X and Y.

Find X^Y and store it in x, i.e. X = X ^ Y.

Again, find X^Y and store it in Y, i.e. Y = X ^ Y.

Find X^Y and store it in X, i.e. X = X ^ Y.

The numbers are swapped.

Answered by SujalSirimilla
5

Answer:

Let's say we have numbers 4 and 10.

I shall use python.

a = 4

b = 10

a = a ^ b;

b = a ^ b;

a = a ^ b;

print ("x = ", x, " y =", y)

⚝──⭒─⭑─⭒──⚝

That's it! output is in the file attached.

Attachments:

anindyaadhikari13: Show workings and how the result came.
SujalSirimilla: sure, i shall edit afterwarda.
Oreki: But what's the advantage of using bitwise operator in Python to swap two numbers when you can just do,
a, b = b, a
SujalSirimilla: Ikt, but a question is a question.
anindyaadhikari13: I got this question in my school project. So, I asked.
Oreki: Hmm, just saying that you could have answered using a different language which doesn't allow as much flexibility as Python does so, it might have been practical to use it in a program in that specific language.
Nevertheless, it's a good answer.
SujalSirimilla: @anindhiyadhikaari did not mention what programming language. So I used python :).
SujalSirimilla: Anyways I shall edit afterwards, I dont have mood to answer/edit lol.
Oreki: Yeah, you are right
anindyaadhikari13: You can use any language.. i don't face any problem to understand.
Similar questions