[Swift] 피보나치 수열 만들어보기

2020. 4. 14. 19:07컴퓨터언어/Swift

728x90
반응형

답이 여럿이겠지만,

 

끄적여 보았다.

class Fibonacci {
   
    func fibonacci(n: Int) {
            
        var fiboArray = [0,1]
        var index = 0
        
        func sum(a: Int, b: Int) -> Int {
            return a + b
        }
        
        if n == 1 {
            print([fiboArray[0]])
        } else if n == 2 {
            print([fiboArray[0], fiboArray[1]])
        } else if n >= 3 {
            while index < n - 2 {
                let nextNumber = sum(a: fiboArray[index], b: fiboArray[index+1])
                fiboArray.append(nextNumber)
                index += 1
            }
            print(fiboArray)
        } else {
            print("Please hit 0~93 in Integer.")
        }
        
    } 
}

let fib = Fibonacci()

fib.fibonacci(n: 93)

 

JS ver.

function fibonacci(n) {
    
    let array = []
    if (n === 1) {
        return [0]
    }
    else if (n === 2) {
        return [0, 1]
    }
    else {
        array = [0, 1]
        while (array.length < n) {
            array.push(array[array.length - 2] + array[array.length - 1])
        }
    	return array
    }
}

728x90
반응형