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
Output: true
Example 2:
Input: 14
Output: false
代码
Approach #1 Binary Search
classSolution {publicbooleanisPerfectSquare(int num) {if (num <2) returntrue;long left =2, right = num /2;int x, guessSquared;while (left <= right) { x = left + (right - left) /2; guessSquared = x * x;if (guessSquared == num) {returntrue; }if (guessSquared > num) { right = x -1; } else { left = x +1; } }returnfalse; }}
Approach #2 Newton's Method
Time O(logN) Space O(1)
classSolution {publicbooleanisPerfectSquare(int num) {if (nums <2) returntrue;long x = num /2;while (x * x > num) { x = (x + num / x) /2; }return (x * x == num); }}