leetcode 367. Valid Perfect Square

来源:互联网 发布:计算机性能测试软件 编辑:程序博客网 时间:2024/06/06 17:51

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) {//1*1末尾1,2*2末尾4,3*3末尾9,4*4末尾6,5*5末尾5,//6*6末尾6,7*7末尾9,8*8末尾4,9*9末尾1,10*10末尾0int mowei=num%10;if(mowei!=0&& mowei!=1 && mowei!=4 && mowei!=5 && mowei!=6 &&mowei!=9){return false;}int sqrt=1;while(sqrt*sqrt<=num){if(sqrt*sqrt==num){return true;}sqrt++;}return false;}
大神表示,平方数都是 1+3+5+7+...,

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
....
so 1+3+...+(2n-1) = (1 + 2n-1 )*n/2 = nn

因此可以这么做:

public boolean isPerfectSquare(int num) {     int i = 1;     while (num > 0) {         num -= i;         i += 2;     }     return num == 0; }

还有一种方法,是用二分查找。

public boolean isPerfectSquare(int num) {        int low = 1, high = num;        while (low <= high) {            long mid = left + (right - left) / 2;            if (mid * mid == num) {                return true;            } else if (mid * mid < num) {                low = (int) mid + 1;            } else {                high = (int) mid - 1;            }        }        return false;}

第三种方法是使用 Newton Method 来计算 square root , refer to Newton Method for details.

public boolean isPerfectSquare(int num) {        long x = num;        while (x * x > num) {            x = (x + num / x) / 2;        }        return x * x == num;    }
[1]: https://en.wikipedia.org/wiki/Newton%27s_method