LeetCode – 1323. Maximum 69 Number

題目連結:

https://leetcode.com/problems/maximum-69-number/

參考解法:

https://leetcode.com/problems/maximum-69-number/discuss/929925/Swift-faster-than-100

法ㄧ(自己的解法):

func maximum69Number (_ num: Int) -> Int {
   var arr: [Int] = []
   var tmp = num
   while tmp > 0 {
       let val = tmp % 10
       tmp = tmp / 10
       arr.append(val)
   }

   var result = 0
   var isReplaced = false
   for i in (0 ..< arr.count).reversed() {
           if !isReplaced && arr[i] == 6 {
               arr[i] = 9
            isReplaced = true
           }
           result = result * 10 + arr[i]
   }

   return result
}

法二(別人的解法):

func maximum69Number (_ num: Int) -> Int {
    var charArr: [Character] = String(num).map { Character("\($0)") }
    if let idx = charArr.firstIndex(of: "6") {
        charArr[idx] = "9"
        return Int(charArr.reduce("") {$0 + String($1)})!
    }
    return num
}


比較法ㄧ和法二performance差異:

//利用這個function去評估performance
func printTimeElapsedWhenRunningCode(title:String, operation:()->()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print("Time elapsed for \(title): \(timeElapsed) s.")
}

法ㄧ: Time elapsed for maximum69Number – 1: 0.0012859106063842773 s.

法二: Time elapsed for maximum69Number – 2: 0.0009620189666748047 s.

法二速度是法ㄧ速度的1.1倍