Problème
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.
Contraintes
−10^18 ≤ n ≤ 10^18
Exemples
Entrée :
n = 49
Sortie attendue :
expected = True
Entrée :
long long n = 49;
Sortie attendue :
bool expected = true;
Entrée :
long n = 49;
Sortie attendue :
bool expected = true;
Explication
49 = 7 × 7, so the answer is true.
Entrée :
n = 50
Sortie attendue :
expected = False
Entrée :
long long n = 50;
Sortie attendue :
bool expected = false;
Entrée :
long n = 50;
Sortie attendue :
bool expected = false;
Explication
7 × 7 = 49 and 8 × 8 = 64, and 50 falls between them, so the answer is false.
Comment l'aborder
Essayez d'abord seul, puis ouvrez les indices un par un.
Indice 1
Find the integer square root r of n first.
Indice 2
n is a perfect square exactly when r × r equals n.
Indice 3
Return false right away for negative numbers.
Complexité attendue
O(log n) time, O(1) extra space
Références
Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.