Given a positive integer num, write a function which returns True if num is a perfect square else False.
Follow up: Do not use any built-in library function such as sqrt
.
Example 1:
Input: num = 16 Output: true
Example 2:
Input: num = 14 Output: false
Constraints:
1 <= num <= 2^31 - 1
有效的完全平方数。
这题做法几乎跟69题一模一样,题意是判断给定的数字是否是一个完全平方数。因为给的input数字有可能很大所以在计算mid的时候需要用long型来处理,否则会超时。
时间O(logn)
空间O(1)
Java实现
1 class Solution { 2 public boolean isPerfectSquare(int num) { 3 // corner case 4 if (num == 1) { 5 return true; 6 } 7 8 // normal case 9 int low = 1; 10 int high = num; 11 while (low <= high) { 12 long mid = low + (high - low) / 2; 13 if (mid * mid == num) { 14 return true; 15 } else if (mid * mid < num) { 16 low = (int) mid + 1; 17 } else { 18 high = (int) mid - 1; 19 } 20 } 21 return false; 22 } 23 }
JavaScript实现
1 /** 2 * @param {number} num 3 * @return {boolean} 4 */ 5 var isPerfectSquare = function(num) { 6 // corner case 7 if (num <= 0) { 8 return false; 9 } 10 if (num === 1) { 11 return true; 12 } 13 14 // normal case 15 let low = 1; 16 let high = num; 17 while (low <= high) { 18 let mid = parseInt(low + (high - low) / 2); 19 if (mid * mid === num) { 20 return true; 21 } else if (mid * mid < num) { 22 low = mid + 1; 23 } else { 24 high = mid - 1; 25 } 26 } 27 return false; 28 };