码迷,mamicode.com
首页 > 其他好文 > 详细

May LeetCoding Challenge9 之 求方差

时间:2020-05-10 10:37:24      阅读:59      评论:0      收藏:0      [点我收藏+]

标签:tco   pytho   判断   coding   python3   public   long   self   perfect   

两种解法:

1.单独判断1,二分法在范围[2,num/2]搜索,如果平方与num相等,则返回true

2.牛顿法

JAVA

class Solution {
    public boolean isPerfectSquare(int num) {
        if(num == 1) return true;
        long left = 2;
        long right = num/2;
        while(left <= right){
            long mid = left + (right-left)/2;
            if(mid*mid == num) return true;
            if(mid*mid > num) right = mid-1;
            else left = mid+1;
        }
        return false;
    }
}

 

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

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

 

Python3

class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        if num == 1:
            return True
        left = 2
        right = num//2
        while left <= right:
            mid = left + (right-left)//2
            if mid*mid == num:
                return True
            if mid*mid > num:
                right = mid - 1
            else:
                left = mid + 1
        return False

 

class Solution:
    def isPerfectSquare(self, num: int) -> bool:
        if num < 2:
            return True
        
        x = num // 2
        while x * x > num:
            x = (x + num // x) // 2
        return x * x == num

 

May LeetCoding Challenge9 之 求方差

标签:tco   pytho   判断   coding   python3   public   long   self   perfect   

原文地址:https://www.cnblogs.com/yawenw/p/12862220.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!