將 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);
}
}