Leetcode 367. Valid Perfect Square

Problem

Given a positive integer num, return true if num is a perfect square or false otherwise.

A perfect square is an integer that is the square of an integer. In other words, it is the product of some integer with itself.

You must not use any built-in library function, such as sqrt.

Algorithm

Use bineary search to get the sqrt root first and then test with accuracy.

Code

class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        L, R = 0, num
        while R - L > 1e-3:
            Mid = (L + R) * 0.5
            if Mid * Mid > num:
                R = Mid
            else: 
                L = Mid
        R = int(R)
        if fabs(num - R*R) < 1e-9:
            return True
        else:
            return False

相关推荐

  1. LeetCode 367, 56, 22

    2024-02-20 22:26:02       24 阅读
  2. Leetcode 367. Valid Perfect Square

    2024-02-20 22:26:02       46 阅读
  3. LeetCode 36

    2024-02-20 22:26:02       36 阅读
  4. Leetcode 377 组合总和 Ⅳ

    2024-02-20 22:26:02       47 阅读
  5. Leetcode 337 打家劫舍 III

    2024-02-20 22:26:02       42 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-20 22:26:02       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-20 22:26:02       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-20 22:26:02       87 阅读
  4. Python语言-面向对象

    2024-02-20 22:26:02       96 阅读

热门阅读

  1. Git面试题整理(基本点)

    2024-02-20 22:26:02       44 阅读
  2. centos8安装docker docker compose

    2024-02-20 22:26:02       53 阅读
  3. 用Dockerfile创建PostgreSQL数据库

    2024-02-20 22:26:02       53 阅读
  4. 习题2.3 old bill

    2024-02-20 22:26:02       46 阅读
  5. Python 实现Excel 文件合并

    2024-02-20 22:26:02       67 阅读
  6. 2024年刷题记录

    2024-02-20 22:26:02       58 阅读
  7. 懒汉单例设计模式与饿汉单例设计模式

    2024-02-20 22:26:02       37 阅读
  8. 【算法训练营】等式,道路升级(c++,python实现)

    2024-02-20 22:26:02       50 阅读
  9. C语言 判断当前存储大小端问题

    2024-02-20 22:26:02       44 阅读