Все задачи
Легко Решено: 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. Следуйте условию и ограничениям выше.

Лучшее принятое решение каждого участника. Более быстрые, экономные и высоко оценённые решения стоят выше.

Принятых решений пока нет. Решите задачу и займите первое место.

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.