Tech for good

[Leetcode/Greedy] 1903. Largest Odd Number in String 본문

IT/Computer Science

[Leetcode/Greedy] 1903. Largest Odd Number in String

Diana Kang 2025. 5. 24. 22:24

class Solution:
    def largestOddNumber(self, num: str) -> str:
        for i in range(len(num)-1, -1, -1):
            if int(num[i]) % 2 == 1:
                return ''.join(num[:i+1])
        return ""
        
        
# 64278
# i = 3
# num = [6, 4, 2, 7, 8]
# num[:i] -> [6, 4, 2]
# num[:i+1] -> [6, 4, 2, 7]

 

 


Backward iteration in Python

range function is provided with three arguments(N, -1, -1). Use this method when we need to modify elements or access their indices.

s = "Python"

# - len(s) - 1: Start at the last index
# - -1: Ensures the loop stops after the first character
# - -1: The step value to iterate backwards
for i in range(len(s) - 1, -1, -1):
    print(s[i])