LeetCode 367. Valid Perfect Square

简介: 给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。

v2-54a1bc5e765fd500d87817e1d6d80057_r.jpg


Description



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


描述



给定一个正整数 num,编写一个函数,如果 num 是一个完全平方数,则返回 True,否则返回 False。


说明:不要使用任何内置的库函数,如 sqrt。


示例 1:

输入:16

输出:True


示例 2:

输入:14

输出:False


思路


  • 用二分法对一个正数开方,如果存在一个正整数 t ,并且 t 的平方等于给定的数,说明该数是完全平方数。
  • 考察基本的二分法。


# -*- coding: utf-8 -*-
# @Author:             何睿
# @Create Date:        2019-06-13 14:35:51
# @Last Modified by:   何睿
# @Last Modified time: 2019-06-13 14:42:06
class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        left, right = 1, num
        while left <= right:
            middle = left + ((right - left) >> 1)
            tmp = middle ** 2
            if tmp == num:
                return True
            elif tmp < num:
                left = middle + 1
            else:
                right = middle - 1
        return False

源代码文件在 这里

目录
相关文章
LeetCode 279. Perfect Squares
给定正整数 n,找到若干个完全平方数(比如 1, 4, 9, 16, ...)使得它们的和等于 n。你需要让组成和的完全平方数的个数最少。
50 0
LeetCode 279. Perfect Squares
LeetCode 242. Valid Anagram
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的一个字母异位词。
53 0
LeetCode 242. Valid Anagram
LeetCode 221. Maximal Square
在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。
42 0
LeetCode 221. Maximal Square
|
canal
LeetCode 125. Valid Palindrome
给定一个字符串,验证它是否是回文串,只考虑字母和数字字符,可以忽略字母的大小写。
65 0
LeetCode 125. Valid Palindrome
|
算法
LeetCode 65. Valid Number
验证给定字符串是否可以解释为十进制数。
64 0
LeetCode 65. Valid Number
Leetcode-Easy 20. Valid Parentheses
Leetcode-Easy 20. Valid Parentheses
88 0
Leetcode-Easy 20. Valid Parentheses
LeetCode 20:有效的括号 Valid Parentheses
给定一个只包括 '(',')','{','}','[',']' 的字符串,判断字符串是否有效。 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. 有效字符串需满足: 左括号必须用相同类型的右括号闭合。
740 0
|
Java
[LeetCode] Valid Parentheses 验证括号是否有效闭合
链接:https://leetcode.com/problems/valid-parentheses/#/description难度:Easy题目:20.
981 0
|
2月前
|
机器学习/深度学习 算法
力扣刷题日常(一)
力扣刷题日常(一)
20 2
|
2月前
|
存储 索引
《LeetCode》—— LeetCode刷题日记
《LeetCode》—— LeetCode刷题日记

热门文章

最新文章