ง่าย 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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก