Coding Exercise 19: Last Digit Checker

2021. 3. 15. 23:09Java programming

Write a method named hasSameLastDigit with three parameters of type int.

 

Each number should be within the range of 10 (inclusive) - 1000 (inclusive).

 

If one of the number is not within the range, the method should return false.

 

The method should return true if at least two of the numbers share the same rightmost digit; otherwise, it should return false.

 

public class LastDigitChecker {
    public static boolean hasSameLastDigit (int number1, int number2, int number3){
        if (number1 >= 10 && number1 <= 1000 && number2 >= 10
                && number2 <= 1000 && number3 >= 10 && number3 <= 1000){

            int rightMostDigit1 = number1 % 10;
            int rightMostDigit2 = number2 % 10;
            int rightMostDigit3 = number3 % 10;
            if (rightMostDigit1 == rightMostDigit2 || rightMostDigit2 == rightMostDigit3
                    || rightMostDigit1 == rightMostDigit3)
            return true;


        } return false;

    }

    public static boolean isValid(int number){
        if (number >= 10 && number <= 1000){
            return true;
        } return false;
    }
}

Within the range of 10 to 1000, if the last digit of at least 2 numbers are same out of 3 numbers given, it should return true based on the boolean system.

 

Like we've been doing from the last several exercises, the last digit will be taken out by using 'number % 10'

 

Another key concept to manipulate this challenge is to apply '&&' in conditions in line with what it asks us to do and what is should be done in using the function of '&&' throughout the exercise.