Applying TDD to reverse a number - part two
Now that you have put the requirements into code, you can go ahead and write the actual implementation! In this follow-up to the previous exercise, you can see much of the same code, including the unit test you just wrote. Your task here is
to use modulo 10 (% 10) to implement the reverse() method.
Este ejercicio forma parte del curso
Introduction to Testing in Java
Instrucciones del ejercicio
- Use
% 10to obtain the last digit of the original number on each iteration. - Discard the last digit of the original number during each iteration using
/ 10.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
public class IntReverser {
public static int reverse(int num) {
int inverted = 0;
while (num != 0) {
// At every iteration take the last digit with % 10 and add to inverted * 10.
inverted = inverted * 10 + ____;
// Discard the last digit using / 10.
num = ____;
}
return inverted;
}
public static class IntReverserTest {
@Test
public void testReverse_reversesNumber() {
int input = 1234;
int expected = 4321;
int actual = IntReverser.reverse(input);
assertEquals(expected, actual);
}
}
public static void main(String[] args) {
launchTestsAndPrint(IntReverserTest.class);
}
}