Swapping 2 numbers without using any temporary variable can be done using arithmetic operations as well, but the algorithm is error-prone. The arithmetic approach will overflow if we try to add Integer.MAX_VALUE
to Integer.MAX_VALUE
.
Bit manipulation technique is the fast and most suitable way to swap 2 numbers.
package org.wesome.dsalgo;
import lombok.AllArgsConstructor;
import lombok.Data;
public class SwapTwoNumber {
public static TwoNumbers swapTwoNumber(TwoNumbers twoNumbers) {
System.out.println("a = " + twoNumbers.a + " b = " + twoNumbers.b);
twoNumbers.a = twoNumbers.a ^ twoNumbers.b;
twoNumbers.b = twoNumbers.a ^ twoNumbers.b;
twoNumbers.a = twoNumbers.a ^ twoNumbers.b;
System.out.println("a = " + twoNumbers.a + " b = " + twoNumbers.b);
return twoNumbers;
}
@Data
@AllArgsConstructor
static class TwoNumbers {
int a;
int b;
}
}
package org.wesome.dsalgo;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SwapTwoNumberTest {
@Test
void swapTwoNumberTest1() {
SwapTwoNumber.TwoNumbers twoNumbers = new SwapTwoNumber.TwoNumbers(1, 2);
SwapTwoNumber.TwoNumbers result = SwapTwoNumber.swapTwoNumber(twoNumbers);
assertAll(() -> assertEquals(2, result.a), () -> assertEquals(1, result.b));
}
@Test
void swapTwoNumberTest2() {
SwapTwoNumber.TwoNumbers twoNumbers = new SwapTwoNumber.TwoNumbers(Integer.MIN_VALUE, Integer.MIN_VALUE);
SwapTwoNumber.TwoNumbers result = SwapTwoNumber.swapTwoNumber(twoNumbers);
assertAll(() -> assertEquals(Integer.MIN_VALUE, result.a), () -> assertEquals(Integer.MIN_VALUE, result.b));
}
@Test
void swapTwoNumberTest3() {
SwapTwoNumber.TwoNumbers twoNumbers = new SwapTwoNumber.TwoNumbers(Integer.MAX_VALUE, Integer.MAX_VALUE);
SwapTwoNumber.TwoNumbers result = SwapTwoNumber.swapTwoNumber(twoNumbers);
assertAll(() -> assertEquals(Integer.MAX_VALUE, result.a), () -> assertEquals(Integer.MAX_VALUE, result.b));
}
@Test
void swapTwoNumberTest4() {
SwapTwoNumber.TwoNumbers twoNumbers = new SwapTwoNumber.TwoNumbers(Integer.MAX_VALUE, Integer.MIN_VALUE);
SwapTwoNumber.TwoNumbers result = SwapTwoNumber.swapTwoNumber(twoNumbers);
assertAll(() -> assertEquals(Integer.MIN_VALUE, result.a), () -> assertEquals(Integer.MAX_VALUE, result.b));
}
}
plugins {
id 'java'
id "io.freefair.lombok" version "6.2.0"
}
group = 'org.wesome'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = JavaVersion.VERSION_1_8
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
testImplementation 'org.junit.jupiter:junit-jupiter:5.6.2'
}
test {
useJUnitPlatform()
}