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

Factorial

Multiply all positive integers up to n.

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

  • Multiply a sequence of numbers with a loop
  • Start a product at 1 instead of 0
  • See how quickly factorials grow

โจทย์

ดูฉบับแปล

The factorial of n, written n!, is 1 × 2 × … × n. By definition 0! = 1.

Implement factorial(n).

Input

n: A non-negative integer.

Output

Return n!.

เงื่อนไข

0 ≤ n ≤ 20, so the result fits a signed 64-bit integer.

ตัวอย่าง

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

ผลลัพธ์ที่คาดหวัง:
expected = 120
อินพุต:
long long n = 5;

ผลลัพธ์ที่คาดหวัง:
long long expected = 120;
อินพุต:
long n = 5;

ผลลัพธ์ที่คาดหวัง:
long expected = 120;

คำอธิบาย

1 × 2 × 3 × 4 × 5 = 120.

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

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

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

ผลลัพธ์ที่คาดหวัง:
long expected = 1;

คำอธิบาย

0! is defined as 1.

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

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

คำใบ้ 1

Factorial multiplies all integers from 1 up to the given number.

คำใบ้ 2

An iterative running product is enough, and 0 has a special defined result.

คำใบ้ 3

Because the input is small, overflow is the main detail to watch for in other languages.

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

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

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

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

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

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

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