zoukankan      html  css  js  c++  java
  • 【leetcode】367. Valid Perfect Square

    题目描述:

    Given a positive integer num, write a function which returns True if num is a perfect square else False.

    解题分析:

    这种找数字的题一般都用类似与二分查找的算法。需要注意的是比较平方和时考虑到integer溢出的情况。所以这个结果是要用Long类型保存。由此到来的改变是判断相等时要用“equals()”方法,而不是“==”。

    实现代码:

     1 public class Solution {
     2     public static boolean isPerfectSquare(int num) {
     3         if(num==1||num==4)
     4             return true;
     5         if(num<=0||num==2||num==3)
     6             return false;
     7         int from=0;
     8         int to=num;
     9         while(from<=to){
    10             int mid = (from+to)/2;
    11             Long result = (long)mid * (long)mid;
    12             if(result.equals(Long.valueOf(num+"")))
    13                 return true;
    14             if(result<num){
    15                 from=mid+1;
    16             }
    17             if(result>num){
    18                 to=mid-1;
    19             }
    20             
    21         }
    22         return false;
    23     }
    24 }

     

  • 相关阅读:
    读《大道至简》第一章有感
    jdk和jre的区别
    题解 LA2911
    题解 UVa11461
    题解 UVa10791
    题解 UVa11489
    题解 LA2889
    题解 UVa11609
    题解 UVa11076
    题解 UVa11752
  • 原文地址:https://www.cnblogs.com/godlei/p/5621981.html
Copyright © 2011-2022 走看看