367. Valid Perfect Square
来源:互联网 发布:脱发用什么药治疗知乎 编辑:程序博客网 时间:2024/06/10 22:43
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: 16Returns: True
Example 2:
Input: 14Returns: False
官方解答:
public boolean isPerfectSquare(int num) { int i = 1; while (num > 0) { num -= i; i += 2; } return num == 0; }
The time complexity is O(sqrt(n)), a more efficient one using binary search whose time complexity isO(log(n)):
public boolean isPerfectSquare(int num) { int low = 1, high = num; while (low <= high) { long mid = (low + high) >>> 1; if (mid * mid == num) { return true; } else if (mid * mid < num) { low = (int) mid + 1; } else { high = (int) mid - 1; } } return false; }
One thing to note is that we have to use long for mid to avoidmid*mid from overflow. Also, you can use long type forlow and high to avoid type casting for mid from long to int.
And a third way is to use Newton Method to calculate the square root or num, refer toNewton Method for details.
public boolean isPerfectSquare(int num) { long x = num; while (x * x > num) { x = (x + num / x) >> 1; } return x * x == num; }
阅读全文
0 0
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square**
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 购物车Recyclerview实现
- 导航条居中显示
- TCP/IP第三层--网络层
- Excel备忘
- vuex官方文档解读
- 367. Valid Perfect Square
- windows server 2008安装Oracle 11g r2先决条件检查失败,提示oracle 交换空间不足的解决方法
- Recyclevire的基本使用
- hexo多终端管理
- Spark Bulkload(Java)
- 推公式。。
- 关于win10环境下安装anaconda后无法启动spyder问题解决
- centos6.9下PHP7.1.10和apache2.4.29安装
- Fragment的show与hide