簡単 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 つずつ開いてみましょう。

ヒント 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用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。