알고리즘/해결

LeetCode1323. Maximum 69 Number

언클린 2020. 3. 8. 18:59
728x90

1. 문제(원본)

Given a positive integer num consisting only of digits 6 and 9.

Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6).

 

Example 1:

Input: num = 9669 Output: 9969 Explanation: Changing the first digit results in 6669. Changing the second digit results in 9969. Changing the third digit results in 9699. Changing the fourth digit results in 9666.  The maximum number is 9969.

Example 2:

Input: num = 9996 Output: 9999 Explanation: Changing the last digit 6 to 9 results in the maximum number.

Example 3:

Input: num = 9999 Output: 9999 Explanation: It is better not to apply any change.

 

Constraints:

  • 1 <= num <= 10^4
  • num's digits are 6 or 9.

2. 문제

임의의 9와 6이 조합되어 있는 수 중에 9와 6을 자유롭게 전환하여 가장 큰 경우의 수를 구하라

3. 나의 답

class Solution {

    func maximum69Number (_ num: Int) -> Int {

        let stringData = String(num)

        var resultList: [String] = [stringData]

        for (index, target) in stringData.enumerated() {

            var makeString = stringData

            makeString.remove(at: makeString.index(makeString.startIndex, offsetBy: index))

            makeString.insert((target == "6") ? "9" : "6", at: makeString.index(makeString.startIndex, offsetBy: index))

            resultList.append(makeString)

        }

        return Int((resultList.sorted().last ?? "0")) ?? 0

    }

}

4. 다른 유저의 답

#1

func maximum69Number (_ num: Int) -> Int {

      var s = Array(String(num))

      if let idx = s.firstIndex(of: "6") {

          s[idx] = "9"

      }

      return Int(String(s)) ?? num

  }

5. 마무리

나름 해설을 보고 모든 경우의 수를 구한 뒤 가장 큰 수를 구하는 방식으로 진행하였는데 다른 유저의 답을 보고 틀에 너무 박혀있었다는 생각이 들었다.

어차피 경우의 수중 앞에 9부터 시작할 수록 큰 수 이므로 최초 6만 9로 바꾼다면 그것이 큰 수가 되는 것이기 때문이다.

문제에 좀 더 독창적으로 접근할 필요를 느낄 수 있었다.

728x90