Day 1: Functions Solution
Hello Friends in this article i am gone to share Hackerrank 10 days of javascript solutions with you. | Day 1: Functions Solution.
Also visit this link:ย Day 1: Arithmetic Operators Solution.
Day 1: Functions Solution
Objective
Today, weโre discussing JavaScript functions. Check out the attached tutorial for more details.ย ย
Task
Implement a function namedย factorialย that has one parameter: an integer,ย n. It must return the value ofย n!ย (i.e.,ย nย factorial).
Input Format
Locked stub code in the editor reads a single integer,ย n, from stdin and passes it to a function namedย factorial.
Constraints
- 1 <=ย nย <= 10
Output Format
The function must return the value ofย n!.
Sample Input 0
4
Sample Output 0
24
Explanation 0
We return the value ofย ย 4! = 4 x 3 x 2 x 1 = 24.
Solution โ Day 1: Functions
'useย strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); letย inputStringย =ย ''; letย currentLineย =ย 0; process.stdin.on('data',ย inputStdinย =>ย { ย ย ย ย inputStringย +=ย inputStdin; }); process.stdin.on('end',ย _ย =>ย { ย ย ย ย inputStringย =ย inputString.trim().split('\n').map(stringย =>ย { ย ย ย ย ย ย ย ย returnย string.trim(); ย ย ย ย }); ย ย ย ย ย ย ย ย main();ย ย ย ย }); functionย readLine()ย { ย ย ย ย returnย inputString[currentLine++]; } /* ย *ย Createย theย functionย factorialย here ย */ functionย factorial(n)ย { ย ย ย ย ifย (nย <ย 2){ ย ย ย ย ย ย ย ย returnย 1; ย ย ย ย } ย ย ย ย returnย nย *ย factorial(n-1); } functionย main()ย { ย ย ย ย constย nย =ย +(readLine()); ย ย ย ย ย ย ย ย console.log(factorial(n)); }