본문 바로가기
프로그래머스/Level_0

[프로그래머스] Lv.0 - 연속된 수의 합.py

by ro-jun 2026. 4. 6.
반응형

문제

  • 연속된 세 개의 정수를 더해 12가 되는 경우는 3, 4, 5입니다. 두 정수 num과 total이 주어집니다. 연속된 수 num개를 더한 값이 total이 될 때, 정수 배열을 오름차순으로 담아 return하도록 solution함수를 완성해보세요.

제한사항

  • 1 ≤ num ≤ 100
  • 0 ≤ total ≤ 1000
  • num개의 연속된 수를 더하여 total이 될 수 없는 테스트 케이스는 없습니다.

입출력 예

코드1

def solution(num, total):
    answer = []
    center = (total // num)
    if num % 2 == 1:
        for n in range(center - (num//2), center + (num//2) + 1):
            answer.append(n)

    else:
        for n in range(center+1 - (num//2), center + (num//2) + 1):
            answer.append(n)
    return answer

출처: 프로그래머스 코딩 테스트 연습, https://school.programmers.co.kr/learn/challenges

반응형