Tutte le sfide
Facile 0 risolte 0% di accettazione

Perfect Square Check

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

−10^18 ≤ n ≤ 10^18

Esempi

Esempio 1
Input:
n = 49

Output atteso:
expected = True
Input:
long long n = 49;

Output atteso:
bool expected = true;
Input:
long n = 49;

Output atteso:
bool expected = true;

Spiegazione

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

Esempio 2
Input:
n = 50

Output atteso:
expected = False
Input:
long long n = 50;

Output atteso:
bool expected = false;
Input:
long n = 50;

Output atteso:
bool expected = false;

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

Find the integer square root r of n first.

Suggerimento 2

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

Suggerimento 3

Return false right away for negative numbers.

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.