Show problems as
Classic problem #509EasyMathDynamic ProgrammingRecursionMemoization

Fibonacci Number

Real-world version: Cascade Register Reading
Tracked in this browser only
Read Fibonacci Number on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

Learn the pattern firstBasic Recursive Functions · Recursion, animated step by step

A ramp generator on a test rig publishes a numbered stream of readings. Reading 0 comes out as 0 and reading 1 comes out as 1. From then on the register produces reading k by totalling the two readings it published immediately beforehand, that is reading k - 1 and reading k - 2.

The stream therefore opens 0, 1, 1, 2, 3, 5, 8 and carries on.

Given an index n, return reading n.

Examples

Example 1

Input
n = 0
Output
0

The stream opens on 0, and no totalling is needed.

Example 2

Input
n = 7
Output
13

Readings 5 and 6 come out as 5 and 8, and totalling them gives reading 7.

Example 3

Input
n = 16
Output
987

Working up the stream one reading at a time reaches 987 at index 16.

Constraints

  • 0 <= n <= 30

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def cascade_reading(n: int) -> int:
Java
public int cascadeReading(int n)