In: Computer Science
Write a function called evenUp that returns the result of increasing the first even digit in a positive integer parameter by 1. (Your solution should use no more than 10 lines of code. Your function can return any convenient value of your choice if the parameter is not positive.) For example, a program that uses the function evenUp follows.
public class P5 {
public static void main(String args[]) {
System.out.println(evenUp(1232)); // prints 1332 only the first even 2 changes
System.out.println(evenUp(1332)); // prints 1333
System.out.println(evenUp(1333)); // prints 1333 no even digit to change
System.out.println(evenUp(22)); // prints 32 System.out.println(evenUp(2)); // prints 3
CODE:
public class P5
{
//Definition for evenUp()
int evenUp(int a){
//converting int to string
String s = ""+a;
// iterating digits
for(int i=0;i<s.length();i++){
//if even digit found
if((s.charAt(i)-'0')%2==0){
// converting character into int and incrementing by 1
int n= s.charAt(i)-'0'+1;
//converting incremented digit into string
String ch = ""+n;
//updating string with updated digit
s = s.substring(0, i) + ch + s.substring(i + 1);
//terminating the loop
break;
}
}
//converting string to int
a = Integer.parseInt(s);
//returns result
return a;
}
public static void main(String[] args) {
//creating object of P5 Class
P5 ob = new P5();
//Calling evenUp() and printing results
System.out.println(ob.evenUp(1232)); // prints 1332
only the first even 2 changes
System.out.println(ob.evenUp(1332)); // prints 1333
System.out.println(ob.evenUp(1333)); // prints 1333 no even digit
to change
System.out.println(ob.evenUp(22)); //prints 32
}
}
OUTPUT: