Largest Odd Number in String | LeetCode 1903 | Python | Solution

LeetCode 1903

It’s a simple problem. We have to return the largest odd number from the given string. If we check odd numbers from the last, we will get the result. If a number is odd, we can say that all the numbers from start to including this number are odd.

Suppose the given number is ‘1234’, and if we start checking it from the end, that’s what we get.

'1234' => 4 is even number
'123' => 3 is odd number
So we can return the whole number from the start to '3', and the result will be: '123'

There is a chance that all the numbers are even. In that case, we will return an empty string.

'24' => 4 is even
'2' => 2 is also even
''

The given number will be in a string. So we can run a loop from the end easily. And we all know how to check odd numbers using the % operator.

Let’s see the code for better understanding.

class Solution:
    def largestOddNumber(self, num: str) -> str:
        
        i = len(num)-1
        
        while i >= 0:
            
            if int(num[i]) % 2 != 0:
                return num[:i+1]
        
            i -= 1
        
        return ""

I hope you got the idea of the problem and the solution.
Happy Learning.
Happy Coding.