BaşlayınÜcretsiz Başlayın

Edge case: Digits of a number

A common programming exercise involves taking the digits of an integer and rearranging them in some way. The fastest way to get the last digit of an integer is to use modulo 10 (% 10). This returns the remainder when dividing the integer by 10.

Here is a method that returns the last digit of an integer. The method fails for exactly half of all possible inputs, negative numbers. This is because modulo 10 preserves the integer's sign.

Input an integer value that causes the lastDigit() method to return an incorrect value.

Bu egzersiz

Introduction to Testing in Java

kursunun bir parçasıdır
Kursu Görüntüle

Egzersiz talimatları

  • Write a multi-digit integer whose last digit is not correctly identified by the lastDigit() method.

Uygulamalı interaktif egzersiz

Bu örnek kodu tamamlayarak bu egzersizi bitirin.

public class LastDigit {
    public static void main(String[] args) {
    	// Write down an integer that causes an incorrect return value of lastDigit()
    	int n = ____; 
        System.out.println("The last digit of " + n + " equals " + lastDigit(n) + ".");
    }

    public static int lastDigit(int a) {
        return a % 10;
    }
}
Kodu Düzenle ve Çalıştır