LeetCode: Find Greatest Common Divisor of Array Solution
Straight forward: min, max then gcdApproach
Straight forward:
- find max
- find min
- find gcd between max of min
JavaScript has no built-in gcd function, so we have to implement from scratch
1function gcd(a, b) {2 if (a % b === 0) {3 return b4 }5 return gcd(b, a % b)6}
Implementation
1var findGCD = function (nums) {2 function gcd(a, b) {3 if (a % b === 0) {4 return b5 }6 return gcd(b, a % b)7 }89 const max = Math.max.apply(null, nums)10 const min = Math.min.apply(null, nums)1112 return gcd(max, min)13}
Comments
Loading comments...
Tags
leetcode
array
math
Apply and earn a $2,500 bonus once you're hired on your first job!
Clients from the Fortune 500 to Silicon Valley startups
Choose your own rate, get paid on time
From hourly, part-time, to full-time positions
Flexible remote working environment
A lot of open JavaScript jobs!!
Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.
Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.
Next Post
LeetCode: Length of Last Word
One-line KO
Previous Post
LeetCode: Rotate List
Should draw for better imagination of how it works