简体   繁体   中英

Method that changes even digits to zero

I need to write a method that receives a number, and for any even digits in it, replaces them with the 0 digit.

I think I'm going in the right direction, but when I run it with the debugger, I seen the even numbers don't return to 0 in even digit.

This is what I have so far.

I know my English is poor, so here's an example example.

For the number 12345, the method should return 10305 For the number 332, the method should return 330.

I hope that's understandable. Here's my code:

public class Assignment1 {

    public static void main(String[] args) {
        System.out.println(Even(12345));
    }

    private static int Even(int n) {    
        if (n == 0 ) { 
            return 0 ;
        }
        if (n % 2 == 0) { // if its even
            n= n/10*10; // we cut the right digit from even number to 0
            return (n/10 %10 ) + Even(n/10)*0;
        }
        return Even(n/10)*10 +n;
    }
}

Your base case is only checking if the number is zero. Check this solution, and let me know if you have doubts!

public int evenToZero(int number){

  //Base case: Only one digit
  if(number % 10 == number){
    if(number % 2 == 0){
      return 0;
    }
    else{
      return number
    }
  }
  else{ //Recursive case: Number of two or more digits
    //Get last digit
    int lastDigit = number % 10;
    //Check if it is even, and change it to zero
    if(lastDigit % 2 == 0){
      lastDigit = 0;      
    }
    //Recursive call
    return evenToZero(number/10)*10 + lastDigit
  }    
}

Below is a recursive method that will do what you need. Using strings will be easier because it allows you to 'add' the number digit by digit. That way, using 332 as example, 3+3+0 becomes 330, and not 6.

Every run through, it cuts of the digit furthest right so 332 becomes 33, then 3, and then 0.

public static void main(String[] args) {
            System.out.println(Even(12345));
        }
        private static String Even(int n) {    
            if(n==0)
                return "";
            else if(n%2==0){
                return Even(n/10) + "0";
            }
            else{
                String s = Integer.toString(n%10);
                return Even(n/10) + s;
            }
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM