Untitled
unknown
plain_text
a year ago
1.9 kB
18
Indexable
package STRINGS;
import java.util.Scanner;
public class LargestOddString {
/**
* This class Takes a string s as Input, representing a large integer, the task is to return the largest-valued odd integer (as a string) that is a substring of the given string s.
* The number returned should not have leading zero's. But the given input string may have leading zero. (If no odd number is found, then return empty string.)
* ex :
*
* Input : s = "5347"
* Output : "5347"
* Explanation : The odd numbers formed by given strings are --> 5, 3, 53, 347, 5347.
* So the largest among all the possible odd numbers for given string is 5347.
*
* Input : s = "0214638"
* Output : "21463"
* Explanation : The different odd numbers that can be formed by the given string are --> 1, 3, 21, 63, 463, 1463, 21463.
* We cannot include 021463 as the number contains leading zero
* So largest odd number in given string is 21463.
*/
public static String LargestOdd (String s){
int ledZero = 0;
int lastOdd = -1;
for (int i = 0; i < s.length(); i++){
if ( s.charAt(i) == '0'){
ledZero++;
}else{
break;
}
}
for (int i = s.length() - 1; i >= ledZero; i--){
int digit = s.charAt(i) - '0';
if (digit % 2 != 0){
lastOdd = i;
break;
}
}
if (lastOdd == -1) {
return "";
} else {
return s.substring(ledZero,lastOdd + 1 );
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("ENTER A NUMBER -> ");
String userInput = s.nextLine();
System.out.println(LargestOdd(userInput));
}
}
Editor is loading...
Leave a Comment