Valid Perfect Square
来源:互联网 发布:易语言源码与模块解析 编辑:程序博客网 时间:2024/04/29 09:11
题目地址:https://leetcode.com/problems/valid-perfect-square/?tab=Description
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
如果可以用内置的sqrt,那就方便多了:
public class ValidPerfectSquare { public boolean isPerfectSquare(int num) { int temp = (int) Math.sqrt(num); if (temp * temp == num) return true; else return false; }}
但是人家说了,不让用内置的方法,那只能想其他办法了,从0
到num
慢慢往上扫呗,可是这个速度貌似有点慢。
我们知道一般在
public class ValidPerfectSquare { public static boolean isPerfectSquare(int num) { int l = 0; int h = 46340; // (int)Math.sqrt(Integer.MAX_VALUE); while (l <= h) { if (l * l == num ||h * h == num) return true; int m = l + (h - l) / 2; if (m * m > num) h = m - 1; else if (m * m == num) return true; else l = m + 1; } return false; } public static void main(String[] args) { for (int i = 2146225; i <= 2146225; i++) System.out.println(i + " " + isPerfectSquare(i)); }}
注意这里可能整型溢出的情况,为了避免这个情况的发生,我们索性就在Integer这个范围内找。
0 0
- 141.Valid Perfect Square
- 367. Valid Perfect Square
- LeetCode:Valid Perfect Square
- 【Leetcode】valid perfect square
- [leetcode] Valid Perfect Square
- 367. Valid Perfect Square
- leetcode367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- Valid Perfect Square
- leetcode---Valid Perfect Square
- 367. Valid Perfect Square
- Valid Perfect Square
- Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- 367. Valid Perfect Square
- Controller页面乱码的问题(修改tomcat默认的编码方式 )
- Class.newInstance()学习
- iOS【终极方案】精准获取webView内容高度,自适应高度
- html/js/css学习之路
- 找位置(简单模拟)
- Valid Perfect Square
- js删除数组中某个特定的对象
- webpack+Vue.js+vue-router的一个简单实例应用
- MxCAD5.2 2017.2.23更新
- webview使用
- 1096. Consecutive Factors (20)
- 用UUID生成唯一识别码
- 服务注册与发现
- HDU 1950 Bridging signals (最长递增子序列(nlogn算法)