You are given a string num
consisting of digits only. Return the largest-valued odd number that is a non-empty substring of num
, or an empty string “” if no odd number exists.
num
will be between 1 and 10^5.num
contain only numeric characters?
Here’s the Python code to solve the problem:
def largestOddNumber(num: str) -> str:
# Loop from the end of the string to the beginning
for i in range(len(num) - 1, -1, -1):
# Check if the character is an odd digit
if int(num[i]) % 2 != 0:
# Return the substring from the start to this odd digit
return num[:i+1]
# Return an empty string if no odd digit is found
return ""
# Example usage:
print(largestOddNumber("52")) # Output: "5"
print(largestOddNumber("4206")) # Output: ""
print(largestOddNumber("35427")) # Output: "35427"
This ensures that the solution is efficient and works within the constraints provided.
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?