zoukankan      html  css  js  c++  java
  • 367. Valid Perfect Square java solutions

    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
    

    Credits:
    Special thanks to @elmirap for adding this problem and creating all test cases.

    Subscribe to see which companies asked this question

    解法一:
     1 public class Solution {
     2     public boolean isPerfectSquare(int num) {
     3         if(num < 0) return false;
     4         if(num == 1) return true;
     5         for(int i = 1; i<= num/i;i++){
     6             if(i*i == num) return true;
     7         }
     8         return false;
     9     }
    10 }

    解法2:  二分查找法 (java 没有ac 仅供参考)

     1 public class Solution {
     2     public boolean isPerfectSquare(int num) {
     3         if(num < 0) return false;
     4         if(num == 1) return true;
     5         int low = 0, high = num/2;
     6         while(low <= high){
     7             long mid = (low + high)/2;
     8             long tmp = mid*mid;
     9             if(tmp == num) return true;
    10             if(tmp > num) high = mid - 1;
    11             else low = mid + 1;
    12         }
    13         return false;
    14     }
    15 }

    解法3:https://leetcode.com/discuss/110659/o-1-time-c-solution-inspired-by-q_rsqrt   大神的 O(1)  解法。

    解法4:

    完全平方数是一系列奇数之和,例如:

    1 = 1
    4 = 1 + 3
    9 = 1 + 3 + 5
    16 = 1 + 3 + 5 + 7
    25 = 1 + 3 + 5 + 7 + 9
    36 = 1 + 3 + 5 + 7 + 9 + 11
    ....
    1+3+...+(2n-1) = (2n-1 + 1)n/2 = n*n

     1 public class Solution {
     2     public boolean isPerfectSquare(int num) {
     3         int i = 1;
     4         while (num > 0) {
     5             num -= i;
     6             i += 2;
     7         }
     8         return num == 0;
     9     }
    10 }
  • 相关阅读:
    算法导论
    深度探索C++对象模型
    git 介绍及其使用总结
    前端跨域常见的几种方式
    前端面试angular 常问问题总结
    低版本浏览器支持HTML5标签的方法
    理解 angular 的路由功能
    Angular 新手容易碰到的坑
    Angular 新手容易碰到的坑
    一 Unicode和UTF-8的异同
  • 原文地址:https://www.cnblogs.com/guoguolan/p/5619443.html
Copyright © 2011-2022 走看看