zoukankan      html  css  js  c++  java
  • May LeetCoding Challenge9 之 求方差

    两种解法:

    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
  • 相关阅读:
    巡回赛 -- 简单的拓扑排序
    最简单的拓扑排序
    blockhouses
    部分和问题
    jfinal路由简单解析
    python mysql
    Gradle--ubuntu
    解决ssh登录后闲置时间过长而断开连接
    业界有很多MQ产品
    avalon---qunar ued
  • 原文地址:https://www.cnblogs.com/yawenw/p/12862220.html
Copyright © 2011-2022 走看看