모든 챌린지
쉬움 0명 해결 정답률 0%

Output Range With Increment

List the numbers from a start value toward an end value, moving by a fixed step.

배우게 될 내용

  • Write a loop with a custom step
  • Choose the counting direction from the inputs
  • Return an empty result for invalid input

문제

번역본 보기

Write a function that lists numbers from start to end, moving by step each time. If start is less than or equal to end, count up: start, start + step, start + 2·step, ... while the value is at most end. If start is greater than end, count down by step instead while the value is at least end. The last value only equals end when the steps land on it exactly.

Implement range_with_increment(start, end, step).

Input

start: The first number.

end: The limit; it is included only if a step lands on it.

step: The size of each step. It must be positive.

Output

Return the numbers in the order they are produced. If step is 0 or negative, return an empty list.

제약 조건

−1000 ≤ start, end ≤ 1000

−100 ≤ step ≤ 100

예시

예시 1
입력:
start = -15
end = 10
step = 5

예상 출력:
expected = [-15, -10, -5, 0, 5, 10]
입력:
long long start = -15;
long long end = 10;
long long step = 5;

예상 출력:
std::vector<long long> expected = {-15, -10, -5, 0, 5, 10};
입력:
long start = -15;
long end = 10;
long step = 5;

예상 출력:
long[] expected = new long[] {-15, -10, -5, 0, 5, 10};

설명

Counting up by 5 from −15 gives −15, −10, −5, 0, 5, 10, and 10 is reached exactly.

예시 2
입력:
start = 20
end = 5
step = 4

예상 출력:
expected = [20, 16, 12, 8]
입력:
long long start = 20;
long long end = 5;
long long step = 4;

예상 출력:
std::vector<long long> expected = {20, 16, 12, 8};
입력:
long start = 20;
long end = 5;
long step = 4;

예상 출력:
long[] expected = new long[] {20, 16, 12, 8};

설명

start is above end, so count down: 20, 16, 12, 8; the next value 4 is below 5.

접근 방법

먼저 스스로 풀어 본 뒤 힌트를 하나씩 열어 보세요.

힌트 1

Handle a step of 0 or less first, or your loop may never end.

힌트 2

Use two loops: one counting up while the value is at most end, one counting down while it is at least end.

힌트 3

Check the condition before adding each value, so a value past end is never added.

예상 복잡도

O(|end − start| / step) time, O(|end − start| / step) extra space

참고 자료

이 문제는 CodeUtility에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.

코더마다 가장 좋은 통과 풀이입니다. 더 빠르고, 메모리를 덜 쓰고, 평가가 좋은 풀이가 위에 옵니다.

아직 통과한 풀이가 없습니다. 풀어서 1위를 차지하세요.

다른 사람의 풀이 보기

커뮤니티 솔루션

아직 공개된 풀이가 없습니다. 문제를 풀고 첫 풀이를 공유하세요.