[LeetCode] 1979. Find Greatest Common Divisor of Array

Chobby·1일 전
1

LeetCode

목록 보기
644/650

😎풀이

  1. 최대 공약수를 계산하는 헬퍼 함수 정의
  2. nums 오름차 순 정렬
  3. 최소, 최대 수 확인
  4. 최대 수, 최소 수의 최대 공약수 반환환
function findGCD(nums: number[]): number {
    const sorted = nums.toSorted((a, b) => a - b)
    const min = sorted[0]
    const max = sorted.at(-1)
    return gcd(max, min)
};

function gcd(a: number, b: number) {
    if(a % b === 0) return b
    return gcd(b, a % b)
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글