# 367.Valid-Perfect-Square

## 367. Valid Perfect Square

## 题目地址

<https://leetcode.com/problems/valid-perfect-square/>

## 题目描述

```
Given a positive integer num, write a function which returns True if num is a perfect square else False.

Note: Do not use any built-in library function such as sqrt.

Example 1:
Input: 16
Output: true

Example 2:
Input: 14
Output: false
```

## 代码

### Approach #1 Binary Search

```java
class Solution {
  public boolean isPerfectSquare(int num) {
        if (num < 2)    return true;

    long left = 2, right = num / 2;
    int x, guessSquared;
    while (left <= right) {
      x = left + (right - left) / 2;
      guessSquared = x * x;
      if (guessSquared == num) {
        return true;
      }
      if (guessSquared > num) {
        right = x - 1;
      } else {
        left = x  + 1;
      }
    }

    return false;
  }
}
```

### Approach #2 Newton's Method

Time `O(logN)` Space `O(1)`

```java
class Solution {
  public boolean isPerfectSquare(int num) {
    if (nums < 2) return true;

    long x = num / 2;
    while (x * x > num) {
      x = (x + num / x) / 2;
    }

    return (x * x == num);
  }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/array/367.valid-perfect-square.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
