Trailing Recursion - Swift


  • 0
    class Solution {
        func maximumSwap(_ num: Int) -> Int {
            if num == 0 {
                return 0
            }
            
            var digits = digitsFromNum(num)
            
            maxDigits(0, digits.count - 1, &digits)
            
            return numFromDigits(digits)
        }
        
        private func maxDigits(_ start: Int, _ end: Int, _ digits: inout [Int]) {
            if start > end {
                return
            }
            
            var maxDigit = 0
            var maxIndex = 0
            
            for i in start...end {
                if digits[i] > maxDigit {
                    maxDigit = digits[i]
                    maxIndex = i
                }
            }
            
            if maxDigit != digits[end] {
                swap(&digits[end], &digits[maxIndex])
                return
            }
            
            maxDigits(start, end - 1, &digits)
        }
        
        private func digitsFromNum(_ num: Int) -> [Int] {
            var digits = [Int]()
            var num = num
            
            while num != 0 {
                digits.append(num % 10)
                num /= 10
            }
    
            return digits
        }
        
        private func numFromDigits(_ digits: [Int]) -> Int {
            var num = 0
            
            for i in 0..<digits.count {
                num += Int(pow(10, Double(i))) * digits[i]
            }
            
            return num
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.