LeetCode in Kotlin

2648. Generate Fibonacci Sequence

Easy

Write a generator function that returns a generator object which yields the fibonacci sequence.

The fibonacci sequence is defined by the relation Xn = Xn-1 + Xn-2.

The first few numbers of the series are 0, 1, 1, 2, 3, 5, 8, 13.

Example 1:

Input: callCount = 5

Output: [0,1,1,2,3]

Explanation:

const gen = fibGenerator(); 
gen.next().value; // 0 
gen.next().value; // 1 
gen.next().value; // 1 
gen.next().value; // 2 
gen.next().value; // 3

Example 2:

Input: callCount = 0

Output: []

Explanation: gen.next() is never called so nothing is outputted

Constraints:

Solution

function* fibGenerator(): Generator<number, any, number> {
    let first = 0
    let second = 1
    let value = 0
    let count = 0
    while (true) {
        if (count <= 1) {
            count++
            yield value++
        } else {
            value = first + second
            first = second
            second = value
            yield value
        }
    }
}

/*
 * const gen = fibGenerator();
 * gen.next().value; // 0
 * gen.next().value; // 1
 */

export { fibGenerator }
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy