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

Square a Number

Multiply an integer by itself.

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

  • Write a function that takes and returns a number
  • Multiply a value by itself
  • Handle negative inputs

โจทย์

ดูฉบับแปล

Return n multiplied by itself. The square of a negative number is positive.

Implement square_number(n).

Input

n: Any integer in the allowed range.

Output

Return n × n.

เงื่อนไข

−3,000,000,000 ≤ n ≤ 3,000,000,000, so the square fits a signed 64-bit integer.

ตัวอย่าง

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

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

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

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

คำอธิบาย

12 × 12 = 144.

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

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

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

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

คำอธิบาย

(−7) × (−7) = 49.

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

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

คำใบ้ 1

This is a direct multiplication problem, even for negative inputs.

คำใบ้ 2

A number times itself always gives a nonnegative result.

คำใบ้ 3

Watch for overflow in languages with fixed-size integers, though the result fits 64 bits here.

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

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

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

# นักโค้ด ภาษา เวลา หน่วยความจำ คะแนนจาก AI คำตอบ
1 HJhettory Jurash Python 979 ms - 5/5 ดูโค้ด
2 GTGarlic The Destroyer Rust 1,572 ms - 5/5 ดูโค้ด

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

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

สปอยล์: มีคำตอบเต็ม 2 ข้อด้านล่าง ลองแก้ด้วยตัวเองก่อน คุณยังสามารถดูโค้ดของนักพัฒนาคนอื่นและรีวิว AI ได้ เข้าสู่ระบบและแก้โจทย์เพื่อร่วมพูดคุย