Printing number using recursion in java without its biggest digit

user11340251 :

Using recursion I need to input a number and the console will print this number without its highest digit. If it's smaller than 10 it will return 0.

I already found the biggest digit but how can i remove it and print the number without it after? This is the code for the biggest digit:

public static int remLastDigit(int n){

        if(n==0)                              
            return 0;
        return Math.max(n%10, remLastDigit(n/10)); 

    }

If i input 12345 i expect the output to be 1234. if i input 9 or less i expect the output to be 0.

Sweeper :

Here is my solution:

// call this method
public static int removeLastDigit(int number) {
    return removeLastDigitImpl(number, largestDigit(number));
}

private static int removeLastDigitImpl(int number, int largestDigit) {
    if (number < 10) { // if the number is a single digit, decide what to do with it
        if (number == largestDigit) {
            return 0; // if it is the largest digit, remove it
        } else {
            return number; // if it is not, keep it
        }
    }
    // handle the last digit of the number otherwise
    if (number % 10 == largestDigit) {
        // removing the digit
        return removeLastDigitImpl(number / 10, largestDigit);
    } else {
        // not removing the digit
        return removeLastDigitImpl(number / 10, largestDigit) * 10 + number % 10;
    }
}

// this is the same as your attempt
private static int largestDigit(int n){

    if(n==0)
        return 0;
    return Math.max(n%10, largestDigit(n/10));

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=166903&siteId=1
Recommended