Get startedGet started for free

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.

This exercise is part of the course

Introduction to Testing in Java

View Course

Exercise instructions

  • Use % 10 to obtain the last digit of the original number on each iteration.
  • Discard the last digit of the original number during each iteration using / 10.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

import org.junit.jupiter.api.Test;

import static com.datacamp.util.testing.CustomJUnitTestLauncher.launchTestsAndPrint;
import static org.junit.jupiter.api.Assertions.assertEquals;

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);
    }
}
Edit and Run Code