资讯专栏INFORMATION COLUMN

[LeetCode] Valid Perfect Square

acrazing / 1876人阅读

Problem

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.

Examples

Example 1:

Input: 16
Returns: True

Example 2:

Input: 14
Returns: False
Solution Newton"s method, close to O(1)
public class Solution {
    public boolean isPerfectSquare(int num) {
      if (num < 1) return false;
      long t = num/2+1;
      while (t*t > num) {
        t = (t+num/t)/2;
      }
      return t*t == num;
    }
}
Binary-Search method, O(logn)
public class Solution {
    public boolean isPerfectSquare(int num) {
        long start = 1, end = num;
        while (start <= end) {
            long mid = start + (end-start)/2;
            long t = mid * mid;
            if (t == num) return true;
            else if (t < num) start = mid+1;
            else end = mid-1;
        }
        return false;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/64981.html

相关文章

  • [LeetCode] 367. Valid Perfect Square

    Problem Given a positive integer num, write a function which returns True if num is a perfect square else False. Example For example:Given num = 16Returns True Solution class Solution { public boo...

    sean 评论0 收藏0
  • [LintCode/LeetCode] Perfect Squares

    摘要:动态规划法建立空数组从到每个数包含最少平方数情况,先所有值为将到范围内所有平方数的值赋两次循环更新,当它本身为平方数时,简化动态规划法四平方和定理法 Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) whi...

    sydMobile 评论0 收藏0
  • [Leetcode] Perfect Squares 完美平方数

    摘要:动态规划复杂度时间空间思路如果一个数可以表示为一个任意数加上一个平方数,也就是,那么能组成这个数最少的平方数个数,就是能组成最少的平方数个数加上因为已经是平方数了。 Perfect Squares Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4...

    Moxmi 评论0 收藏0
  • [LeetCode] 279. Perfect Squares

    Problem Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 16, ...) which sum to n. Example 1: Input: n = 12Output: 3 Explanation: 12 = 4 + 4 + 4.Exampl...

    mist14 评论0 收藏0
  • leetcode279. Perfect Squares

    摘要:题目要求判断一个数字最少由几个平方数的和构成。思路一暴力递归要想知道什么样的组合最好,暴力比较所有的结果就好啦。当然,效率奇差。代码如下思路三数学统治一切这里涉及了一个叫做四平方定理的内容。有兴趣的可以去了解一下这个定理。 题目要求 Given a positive integer n, find the least number of perfect square numbers (...

    reclay 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<