Leetcode 1903. Largest Odd Number in String
Given a string num
, which represents a large integer, return the largest-valued odd number (as a substring) that is actually a contiguous substring of num
. If no odd number exists, return an empty string “”.
Based on common problem setups, it is usually safe to assume:
num
contains only digits and may be empty.To find the largest odd number as a contiguous substring:
This approach is efficient since you only need to traverse the string once from the end to the start.
n
is the length of the input string. This is because we might need to traverse the entire string in the worst case.public class Solution {
public String largestOddNumber(String num) {
// Iterate from the end to the beginning to find the first odd digit
for (int i = num.length() - 1; i >= 0; i--) {
char c = num.charAt(i);
if ((c - '0') % 2 != 0) {
// Return the substring up to and including this odd digit
return num.substring(0, i + 1);
}
}
// If no odd digit is found, return an empty string
return "";
}
// Main function for quick testing
public static void main(String[] args) {
Solution solution = new Solution();
System.out.println(solution.largestOddNumber("52")); // "5"
System.out.println(solution.largestOddNumber("4206")); // ""
System.out.println(solution.largestOddNumber("35427")); // "35427"
}
}
largestOddNumber
which takes a string num
as input.num
to this position.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?