[LeetCode][Python]367. 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
Returns: True

Example 2:

Input: 14
Returns: False

思路:所谓perfect Square,A perfect square is a number that can be expressed as the** product of two equal integers**.

可以参照perfect number的思路,从1到sqrt(num)依次比对,后来发现会提前跳出循环。突然灵机一动,想出了个取巧的方法。使用Python的**0.5代替sqrt,能被accept,不过好像还是不满足题目要求。

看了其他人的思路,发现还有一个牛顿法,以及二分法查找。二分法查找倒是非常直观。

#!/usr/bin/env python
# -*- coding: UTF-8 -*-
class Solution(object):
    def isPerfectSquare(self, num):
        """
        :type num: int
        :rtype: bool
        """
        return (int(num**0.5)**2)==num

    def isPerfectSquare2(self, num):
        res = num
        while(res*res > num):
            res = (res + num/res) >> 1

        return res*res == num

    def isPerfectSquare3(self, num):
        res = num
        while res*res > num:
            res = (res + num/res)/2
        return res*res == num

    def isPerfectSquare4(self, num):
        low = 1
        high = num
        while(low < high):
            mid = (low + high)/2
            if(mid*mid>num):
                high = mid -1
            elif(mid*mid<num):
                low = mid + 1
            else:
                return True

        return False



if __name__ == '__main__':
    sol = Solution()
    print sol.isPerfectSquare(4)
    print sol.isPerfectSquare(16)
    print sol.isPerfectSquare(14)

    print sol.isPerfectSquare(8)
    print sol.isPerfectSquare(36)

    print sol.isPerfectSquare2(16)
    print sol.isPerfectSquare3(16)

    print sol.isPerfectSquare4(16)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,790评论 0 33
  • 不知不觉,日志已经100篇。想起了刚写的时候还跟朋友开玩笑,我要写到100篇。当时的状态是每天会看看书,情绪高涨,...
    他说他的不说阅读 223评论 0 0
  • 1、先讲一个故事。 传说西塔发明了国际象棋而使国王十分高兴,他决定要重赏西塔,西塔说:“我不要你的重赏 ,陛下,只...
    黄圈圈阅读 651评论 0 1
  • oc用法 [DatePickerViewshowDatePickerWithTitle:@"出生年月"dateTy...
    雪鹰_007阅读 1,407评论 0 0