开始使用免费开始使用

将 TDD 应用于反转数字——第二部分

既然您已经把需求写成了代码,现在就可以开始编写实际的实现了!这是前一个练习的延续,您会看到大部分相同的代码,包括刚刚编写的单元测试。您的任务是使用对 10 取模(% 10)来实现 reverse() 方法。

本练习是课程的一部分

Java 测试入门

查看课程

练习说明

  • 在每次迭代中使用 % 10 获取原数字的最后一位。
  • 在每次迭代中使用 / 10 丢弃原数字的最后一位。

交互式实操练习

通过完成这段示例代码来试试这个练习。

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);
    }
}
编辑并运行代码