yemerra
yemerra

Reputation: 1342

Recursion task in Java

public static boolean sameNumbers(int number) {
    boolean isSame;
    isSame = (number % 10) == (number / 10) % 10;      
    sameNumbers(number / 10);
    return isSame;
}

My task is to implement a method which checks if the given int value has all the same numbers (e.g. 666 or 1111). However, the requirement is that I should just choose recursion and no iteration.

I am aware that my method wouldn't work, but I really don't know how I can solve this problem without any if statements. Any ideas?

Upvotes: 1

Views: 500

Answers (3)

allonhadaya
allonhadaya

Reputation: 1297

For a more spelled out implementation:

public static bool sameNumbers(int number) {
    int onesPlace = number % 10;
    int shifted = number / 10;
    int tensPlace = shifted % 10;
    return onesPlace == number || (onesPlace == tensPlace && sameNumbers(shifted));
}

Depending on your definition of correct, this will handle negative numbers correctly.


If you are allowed to use if statements, this will save you a few instructions:

public static bool sameNumbers(int number) {
    int onesPlace = number % 10;
    if (onesPlace == number) {
        return true;
    }
    int shifted = number / 10;
    int tensPlace = shifted % 10;
    return onesPlace == tensPlace && sameNumbers(shifted);
}

Upvotes: 0

Zong
Zong

Reputation: 6230

You have the right approach. It's just a matter of combining the base case with the recursive component. If you want to avoid if, just do this:

public static boolean sameNumbers(int number) {
    return number < 10 || ((number % 10) == (number / 10) % 10) 
                          && sameNumbers(number / 10));
}

Upvotes: 6

jimbo
jimbo

Reputation: 11042

When tackling a recursion problem, you have to split it into a base case and a recurse case. So for instance, you know that any number with one digit contains all the same digit. That would be your base case.

For numbers with more than one digit, you could check two digits, and fail fast if they don't match. If they do match, then chop one off and return the test against the shortened number.

Upvotes: 0

Related Questions