Tell me the Logic to swap two numbers using bitwise operator?
Answers
Answered by
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
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:
a, b = b, a
Nevertheless, it's a good answer.
Similar questions
English,
2 months ago
Computer Science,
2 months ago
Math,
5 months ago
Social Sciences,
5 months ago
History,
11 months ago
CBSE BOARD X,
11 months ago
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