ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Fizz Buzz

Build a sequence using divisibility by 3 and 5.

สิ่งที่คุณจะได้เรียนรู้

  • Test divisibility by 3 and 5
  • Order if/else branches correctly
  • Build a list of results in a loop

โจทย์

ดูฉบับแปล

For each integer from 1 through limit, use Fizz for multiples of 3, Buzz for multiples of 5, and FizzBuzz for multiples of both. Otherwise use the number written as text. Return the entries in order instead of printing them.

Implement fizz_buzz(limit).

Input

limit: The last integer to include.

Output

Return a list of strings, one for each integer from 1 through limit.

เงื่อนไข

0 ≤ limit ≤ 10,000. A limit of 0 produces an empty list.

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
limit = 5

ผลลัพธ์ที่คาดหวัง:
expected = ["1", "2", "Fizz", "4", "Buzz"]
อินพุต:
long long limit = 5;

ผลลัพธ์ที่คาดหวัง:
std::vector<std::string> expected = {"1", "2", "Fizz", "4", "Buzz"};
อินพุต:
long limit = 5;

ผลลัพธ์ที่คาดหวัง:
string[] expected = new string[] {"1", "2", "Fizz", "4", "Buzz"};

คำอธิบาย

3 is divisible by 3 and 5 is divisible by 5. Other entries keep their number.

ตัวอย่างที่ 2
อินพุต:
limit = 0

ผลลัพธ์ที่คาดหวัง:
expected = []
อินพุต:
long long limit = 0;

ผลลัพธ์ที่คาดหวัง:
std::vector<std::string> expected = {};
อินพุต:
long limit = 0;

ผลลัพธ์ที่คาดหวัง:
string[] expected = new string[] {};

คำอธิบาย

There are no integers from 1 through 0, so the list is empty.

แนวทางการแก้

ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ

คำใบ้ 1

Each position depends only on the current integer’s divisibility by 3 and 5.

คำใบ้ 2

Build the result list in order by checking both divisibility conditions for every number.

คำใบ้ 3

Handle the lower bound carefully: if the limit is 0, the answer is an empty list.

ความซับซ้อนที่คาดหวัง

O(n) time, O(n) extra space

แหล่งอ้างอิง

โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

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

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

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