Skip to content

1903. Largest Odd Number in String 👍

  • Time: $O(n)$
  • Space: $O(n)$
1
2
3
4
5
6
7
8
9
class Solution {
 public:
  string largestOddNumber(string num) {
    for (int i = num.length() - 1; i >= 0; --i)
      if ((num[i] - '0') % 2 == 1)
        return num.substr(0, i + 1);
    return "";
  }
};
1
2
3
4
5
6
7
8
class Solution {
  public String largestOddNumber(String num) {
    for (int i = num.length() - 1; i >= 0; --i)
      if ((num.charAt(i) - '0') % 2 == 1)
        return num.substring(0, i + 1);
    return "";
  }
}
1
2
3
4
5
6
class Solution:
  def largestOddNumber(self, num: str) -> str:
    for i, n in reversed(list(enumerate(num))):
      if int(n) % 2 == 1:
        return num[:i + 1]
    return ''