Swap two bits of integer at given position in scala

Scala program for Swap two specific bits of a integer. Here problem description and other solutions.

``````/*
Scala program for
Swap two bits in an integer
*/
class BitExchange()
{
// Swap two bits in a given decimal number and position
def swapBits(n: Int, a: Int, b: Int): Unit = {
if (a < 0 || b < 0)
{
print("\n Invalid bit position (" + a + "," + b + ")");
return;
}
// Get first bit
var b1: Int = 1 & (n >> a);
// Get Second bit
var b2: Int = 1 & (n >> b);
var result: Int = n;
if (b1 != b2)
{
// When b1 and b2 not same
// Swap bits
result = n ^ ((1 << a) | (1 << b));
}
// Display calculated result
println("\n Number : " + n + "");
println(" Swap bits : (" + a + "," + b + ")");
println(" Output : " + result);
}
}
object Main
{
def main(args: Array[String]): Unit = {
var task: BitExchange = new BitExchange();
// Test cases
// ---------------------
// num = 16 Binary(10000)
// (16) Change bit (1,4)
// 10000 => 00010 (2)
// ↑  ↑
// num = 35 Binary(00100011)
// (35) Change bit (6,0)
// 00100011 (35) =>  01100010 (98)
//  ↑     ↑
//  00001111 (15)  => 11110000 (1s) => (11110001) (2s)
//  11110001 (-15) => Change bit (5,1)
//  11110001 (-15) => 11010011 (-45)
//    ↑   ↑
// 1010 (10) Change bit (1,3)
// ↑ ↑
// Bit value of 1 and 3 are similar
}
}``````

Output

`````` Number : 16
Swap bits : (1,4)
Output : 2

Number : 35
Swap bits : (6,0)
Output : 98

Number : -15
Swap bits : (5,1)
Output : -45

Number : 10
Swap bits : (1,3)
Output : 10``````

Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.