Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java- Builiding a recursion that replace even digits with zero

Tags:

java

recursion

Hello i need to build a recursion that replace the even digits with zero: for exmaple - the number 1254 will be 1050 the number 332- will be 330 and the number 24 - will be 0

i started working on it but got pretty clueless after a while

 public static int replaceEvenDigitsWithZero(int number){
    if(number<1)
        return number;
    if(number%2==0 && number%10!=0){
        int temp=number%10;
        return(number/10+replaceEvenDigitsWithZero(number-temp));
    }
    return(replaceEvenDigitsWithZero(number/10));
}
public static void main(String[] args) {
        int num1 = 1254;
        System.out.println(num1 + " --> " + replaceEvenDigitsWithZero(num1));

        int num2 = 332;
        System.out.println(num2 + " --> " + replaceEvenDigitsWithZero(num2));

        int num3 = 24;
        System.out.println(num3 + " --> " + replaceEvenDigitsWithZero(num3));

        int num4 = 13;
        System.out.println(num4 + " --> " + replaceEvenDigitsWithZero(num4));
    }

}
like image 487
Ido Shapira Avatar asked Apr 29 '26 09:04

Ido Shapira


1 Answers

Since your method only looks at the last digit, it should always call itself with input / 10 when input >= 10.

You then take the value returned by the recursion, multiply it by 10 and add the last digit back, if odd.

public static int replaceEvenDigitsWithZero(int number) {
    int result = 0;
    if (number >= 10)
        result = replaceEvenDigitsWithZero(number / 10) * 10;
    if (number % 2 != 0)
        result += number % 10;
    return result;
}
like image 172
Andreas Avatar answered Apr 30 '26 23:04

Andreas