LeetCode 1903: Largest Odd Number in String Solution

Master LeetCode problem 1903 (Largest Odd Number in String), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

1903. Largest Odd Number in String

Problem Explanation

Explanation:

To solve this problem, we iterate through the given string from right to left and check if the current character is an odd digit. If we find an odd digit, we return the substring from that position to the end of the string. If no odd digit is found, we return an empty string.

  • Start from the rightmost digit of the string.
  • Iterate towards the left.
  • If we encounter an odd digit, return the substring from that position to the end.
  • If no odd digit is found, return an empty string.

Time Complexity: O(n) where n is the length of the input string num. Space Complexity: O(1)

:

Solution Code

class Solution {
    public String largestOddNumber(String num) {
        for (int i = num.length() - 1; i >= 0; i--) {
            if ((num.charAt(i) - '0') % 2 != 0) {
                return num.substring(0, i + 1);
            }
        }
        return "";
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 1903 (Largest Odd Number in String)?

This page provides optimized solutions for LeetCode problem 1903 (Largest Odd Number in String) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 1903 (Largest Odd Number in String)?

The time complexity for LeetCode 1903 (Largest Odd Number in String) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 1903 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1903 in Java, C++, or Python.

Back to LeetCode Solutions