
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Recursive Staircase Problem in JavaScript
Suppose we have the following problem −
There are n stairs, a person standing at the bottom wants to reach the top. The person can climb either 1 or 2 stairs at a time. We are required to count the number of ways, the person can reach the top.
We are required to write a JavaScript function that takes in a number n that denotes the number of stairs. The function should count and return the number of ways in which the stairs can be climbed.
Example
Following is the code −
const recursiveStaircase = (num = 10) => { if (num <= 0) { return 0; } const steps = [1, 2]; if (num <= 2) { return steps[num - 1]; } for (let currentStep = 3; currentStep <= num; currentStep += 1) { [steps[0], steps[1]] = [steps[1], steps[0] + steps[1]]; } return steps[1]; }; console.log(recursiveStaircase()); console.log(recursiveStaircase(4)); console.log(recursiveStaircase(13));
Output
Following is the output on console −
89 5 377
Advertisements