Implement int sqrt(int x)
.
Compute and return the square root of x, where x is guaranteed to be a non-negative integer.
Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.
Example 1:
Input: 4 Output: 2 根据牛顿法 p是要开根的数, 通过计算这个数列即可得到 注意判断时给定的数太大可能会超int
class Solution {
public:
int mySqrt(int x) {
// 牛顿法
long long k = 1;
while(!(k*k <= x && (k+1)*(k+1)>x)){
k = (k + x/k)/2;
}
return k;
}
};