프로그래밍/코딩테스트

[Contest 246] 1903. Largest Odd Number in String / Swift

turu 2021. 6. 21. 00:54

[문제 보기]

더보기

You are given a string num, representing a large integer. Return the largest-valued odd integer (as a string) that is a non-empty substring of num, or an empty string "" if no odd integer exists.

A substring is a contiguous sequence of characters within a string.

 

Example 1:

Input: num = "52" Output: "5" Explanation: The only non-empty substrings are "5", "2", and "52". "5" is the only odd number.

Example 2:

Input: num = "4206" Output: "" Explanation: There are no odd numbers in "4206".

Example 3:

Input: num = "35427" Output: "35427" Explanation: "35427" is already an odd number.

 

Constraints:

  • 1 <= num.length <= 105
  • num only consists of digits and does not contain any leading zeros.

 

https://leetcode.com/problems/largest-odd-number-in-string/


3점짜리 1번문제였다.

 

홀수판별은 끝자리 수가 홀수인지만 확인하면 되는데, 이것을 이용해서

주어진 수의 끝자리 수부터 탐색하면서 그 끝자리 수가 홀수일 때를 찾아서 맨앞부터 찾은홀수 인덱스까지 숫자들을 반환하는 방법으로 해결했다.

예)

123456 -> 끝자리 6부터 1까지 탐색, 가장 먼저 나온 홀수는 5가 되고 맨 앞부터 5까지 숫자인 12345가 가장 큰 홀수가 된다.

 

class Solution {
    func largestOddNumber(_ num: String) -> String {
        let arr = Array(num)
        var latestOddIndex = 0
        for (i, val) in arr.enumerated().reversed() {
            if Int(String(val))! % 2 == 1 {
                latestOddIndex = i + 1
                break
            }
        }
        return String(arr[0..<latestOddIndex])
    }
}
반응형