เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

นำ TDD มาใช้กับการกลับเลข - ส่วนที่สอง

เมื่อแปลงข้อกำหนดเป็นโค้ดแล้ว ก็ถึงเวลาเขียน implementation จริงได้เลย แบบฝึกหัดนี้ต่อเนื่องจากข้อก่อนหน้า โดยมีโค้ดส่วนใหญ่เหมือนเดิม รวมถึง unit test ที่เพิ่งเขียนไป หน้าที่ของคุณคือใช้โมดูโล 10 (% 10) เพื่อ implement เมธอด 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);
    }
}
แก้ไขและรันโค้ด