• + 3 comments

    in swift

    I am getting failed in test case 6,7,8. Any help and suggestion would be appreciated

    import Foundation
    
    var arr: [[Int]] = [[0], [1]]
    
    func calculateNumber(number: Int) -> Int {
        if arr.count > number {
                return arr[number].count
        }
    
        var array = [Int]()
    
        let from = number > 9 ? 9 : number
        for i in stride(from: from, through: 0, by: -1) where (number - i) % 2 == 0 {
                let extraNumber = (number - i) / 2
                if arr.count > extraNumber {
                        for a in arr[extraNumber] {
                                array.append(a * 10 + i)
                        }
                }
        }
    
        array.sort()
        array.reversed()
        arr.append(array)
        return array.count
    }
    
    func decibinaryNumbers(x: Int) -> Int {
        var prevLength = 0
        var length = 0
        var i = 0
        while true {
                length += calculateNumber(number: i)
                if length >= x {
                        break
                }
                i += 1
                prevLength = length
        }
    
        let index = x - prevLength - 1
        return arr[i][index]
    }
    
    let q = Int(readLine()!)!
    
    for _ in 1...q {
        let x = Int(readLine()!)!
        print(decibinaryNumbers(x: x))
    }