学习算法的Day1 二分法处理平方根
平方根有递归、二分法、牛顿迭代法三种方法解决,本文采用二分法(因为day1练习二分法)
题目链接如下:
https://leetcode-cn.com/problems/valid-perfect-square/
代码如下:
class Solution {
public boolean isPerfectSquare(int num) {
long left = 0, right = num / 2;
long mid = 0;
if(num < 2) return true;
while(left <= right){
mid = left + (right - left) / 2;
long guess = mid * mid;
if (guess == num) return true;
if (guess < num) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return false;
}
}
这里需要注意以下几点: