Finding and Printing the First Digit in Ones Place

3163 views java
0

Write a method this passed two integers which returns true if the two numbers x and y have the same number in the ones place.

My Code:

int number;
while( number > 0) {
print (number%10);
number = number/10;

I know this is wrong but I am not sure where to start; I am a beginning coder.

answered question

return x % 10 == y % 10;

1 Answer

3

What you can do is convert the integers to a String and get the character at the last index and see if they are equal.

public void lastDigitEqual(int a, int b){
    String astring = Integer.toString(a);
    String bstring = Integer.toString(b);
    if(astring.charAt(astring.length()-1) == bstring.charAt(bstring.length()-1)){
        System.out.println("True");
    }else{
        System.out.println("False");
    }
}

Or another way of doing it is just getting the numbers mod 10. This will return the remainder of the two numbers when they are divided by 10, which will basically just be the ones digit. Then, you can check if they are equal.

public void lastDigitEqual(int a, int b){
    int amod = a % 10;
    int bmod = b % 10;
    if(bmod == amod){
        System.out.println("True");
    }else{
        System.out.println("False");
    }
}

I tested both these ways and they work.

posted this

Have an answer?

JD

Please login first before posting an answer.