본문 바로가기

프로그래머스(코딩 테스트)/Lv.0

홀짝에 따라 다른 값 반환하기

// javascript
const solution = (n) => {
    return n % 2 === 1 
        ? Array.from({ length: Math.floor(n / 2) + 1 }, (_, index) => index * 2 + 1).reduce((sum, num) => sum + num, 0) 
        : Array.from({ length: n / 2 }, (_, index) => (index + 1) * 2).reduce((sum, num) => sum + num * num, 0);
}
// typescript
const solution = (n: number): number => {
    return n % 2 === 1 
        ? Array.from({ length: Math.floor(n / 2) + 1 }, (_, index) => index * 2 + 1).reduce((sum, num) => sum + num, 0) 
        : Array.from({ length: n / 2 }, (_, index) => (index + 1) * 2).reduce((sum, num) => sum + num * num, 0);
}

'프로그래머스(코딩 테스트) > Lv.0' 카테고리의 다른 글

머쓱이보다 키 큰 사람  (0) 2024.10.15
두 수의 차  (0) 2024.10.15
두 수의 합  (0) 2024.10.15
더 크게 합치기  (0) 2024.10.15
특수문자 출력하기  (0) 2024.10.15