Write a method evenDigits that accepts an integer parameter

Write a method evenDigits that accepts an integer parameter n and that returns the integer formed by removing the odd digits from n. The following table shows several calls and their expected return values: If a negative number with even digits other than 0 is passed to the method, the result should also be negative, as shown above when -34512 is passed. Leading zeros in the result should be ignored and if there are no even digits other than 0 in the number, the method should return 0, as shown in the last three outputs. This is a method problem. Write a Java method as described. Do not write a complete program or class; just the method(s) above.

Solution

EvenDigitsTest.java


public class EvenDigitsTest {

  
   public static void main(String[] args) {
   System.out.println(evenDigits(8342116));
   System.out.println(evenDigits(4109));
   System.out.println(evenDigits(8));
   System.out.println(evenDigits(-34512));
   System.out.println(evenDigits(-163505));
   System.out.println(evenDigits(3052));
   System.out.println(evenDigits(7010496));
   System.out.println(evenDigits(35179));
   System.out.println(evenDigits(5307));
   System.out.println(evenDigits(7));
   }
   public static int evenDigits(int n){
       boolean negFalg = false;
       if(n < 0){
           negFalg = true;
           n = -n;
       }
       int result = 0;
       int n1 = n;
       int length = 0;
       while(n1 > 0){
           length++;
           n1 = n1/10;
       }
       while(length >= 0){
           int diviser = 1;
           for(int i=0; i<length; i++){
               diviser = diviser * 10;
           }
           int r = n / diviser;
           if(r % 2 ==0){
           result = result * 10 + r;
           }
           n = n % diviser;
           length--;
       }
       if(negFalg){
           result = -result;
       }
       return result;
   }

}

Output:

8426
40
8
-42
-60
2
46
0
0
0

 Write a method evenDigits that accepts an integer parameter n and that returns the integer formed by removing the odd digits from n. The following table shows
 Write a method evenDigits that accepts an integer parameter n and that returns the integer formed by removing the odd digits from n. The following table shows

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site