Đề bài
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.
Ràng buộc
−10^18 ≤ n ≤ 10^18
Ví dụ
Đầu vào:
n = 49
Kết quả mong đợi:
expected = True
Đầu vào:
long long n = 49;
Kết quả mong đợi:
bool expected = true;
Đầu vào:
long n = 49;
Kết quả mong đợi:
bool expected = true;
Giải thích
49 = 7 × 7, so the answer is true.
Đầu vào:
n = 50
Kết quả mong đợi:
expected = False
Đầu vào:
long long n = 50;
Kết quả mong đợi:
bool expected = false;
Đầu vào:
long n = 50;
Kết quả mong đợi:
bool expected = false;
Giải thích
7 × 7 = 49 and 8 × 8 = 64, and 50 falls between them, so the answer is false.
Hướng tiếp cận
Hãy tự thử trước, sau đó mở từng gợi ý một.
Gợi ý 1
Find the integer square root r of n first.
Gợi ý 2
n is a perfect square exactly when r × r equals n.
Gợi ý 3
Return false right away for negative numbers.
Độ phức tạp mong đợi
O(log n) time, O(1) extra space
Tham khảo
Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.