zoukankan      html  css  js  c++  java
  • leetcode367- Valid Perfect Square- easy

    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

    算法:1.二分法O(logN)。用mid*mid与num比较。细节是看到这种乘法在中间的都要小心溢出,mid用long格式!!不然如果mid比较大100000乘一下溢出变成负数那你就不能得到正确的比较结果了。

    2.数学法(O(sqrtN))。因为所有的完美平方数都是1+3+5+...得到的,那你就可以这样加下去到逼近它。

    1.二分法(O(logN))

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

    2.O(sqrtN)

    class Solution {
        public boolean isPerfectSquare(int num) {
    
            int sum = 0;
            int digit = 1;
            while (sum < num) {
                sum += digit;
                digit += 2;
            }
            if (sum == num) {
                return true;
            } 
            return false;
        }
    }
  • 相关阅读:
    常用分页插件
    sessionStorage二种存值取值的方法
    $(this).index()与$(obj).index(this)的区别
    每次移1px的无缝轮播图
    为什么全局变量在赋值之前调用会报错
    Number()、parseInt()和parseFloat()的区别
    JSON.parse()与JSON.stringify()
    HDU
    出现负数的01背包问题
    HDU
  • 原文地址:https://www.cnblogs.com/jasminemzy/p/7918411.html
Copyright © 2011-2022 走看看