69.Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x
.
367.Valid Perfect Square
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
这两个题都比较简单,可以用二分查找做,还可以用牛顿法。
//Newton
class Solution {
public:
int mySqrt(int x) {
if (x == 0) return 0;
long r = x;
while (r * r > x)
r = (r + x / r) / 2;
return r;
}
};
//Newton
class Solution {
public:
bool isPerfectSquare(int num) {
if(num < 1) return false;
if(num == 1) return true;
long t = num/2;
while(t*t > num){
t = (t + num/t)/2;
}
return t*t == num;
}
};