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

Perfect Square Check

Decide whether an integer is the square of a whole number.

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

  • Reuse an integer square root to test squares
  • Handle negative inputs
  • Avoid floating point comparisons

โจทย์

ดูฉบับแปล

A perfect square is a number like 0, 1, 4, 9 or 16 that equals k × k for some integer k. Negative numbers are never perfect squares. Check with integer arithmetic so that very large inputs are handled exactly.

Implement perfect_square_check(n).

Input

n: The integer to test. It may be negative.

Output

Return true if n = k × k for some integer k, otherwise false.

เงื่อนไข

−10^18 ≤ n ≤ 10^18

ตัวอย่าง

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

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

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

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

คำอธิบาย

49 = 7 × 7, so the answer is true.

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

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

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

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

คำอธิบาย

7 × 7 = 49 and 8 × 8 = 64, and 50 falls between them, so the answer is false.

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

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

คำใบ้ 1

Find the integer square root r of n first.

คำใบ้ 2

n is a perfect square exactly when r × r equals n.

คำใบ้ 3

Return false right away for negative numbers.

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

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

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

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

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

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

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

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

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