1.Description
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of the result is returned.
2. Test Cases Example
Example 1:
Input: x = 4
Output: 2
Example 2:
Input: x = 8
Output: 2
Explanation: The square root of 8 is 2.82842..., and since the decimal part is truncated, 2 is returned.
3.Solution
3.1
Java里面有开方的函数,那就先试一下。(这显然不是题目要考的点)
class Solution {
public int mySqrt(int x) {
Double sqrt = Math.sqrt(x);
return sqrt.intValue();
}
}
3.2
回想自己如何预估一个整数x的平方根的过程,首先猜一个值a,然后计算a平方值,如果a的平方大于x,那么值取得太大了,可以再换一个小一点的值。直到找到一个值b,他的平方值小于x。那么x的平方根就应该在a与b之间。
但是这个方法的关键在于要能找到一个合适的a,如果是一个超级大的数字,这个初始的a该如何确定?计算机程序那就二分法找好了,但是二分法找,a的平方的值会很大,可能会超出最大整数。可以将int转换为long。
class Solution {
public int mySqrt(int x) {
if (x ==0 || x ==1) return x;
long left = 1;
long end = x;
while (left < end) {
long mid = (left + end ) / 2;
if (mid * mid == x) {
return (int)mid;
}else if (mid * mid > x) {
end = mid;
} else {
left = mid + 1;
}
}
return (int)left -1;
}
}
本文介绍了一种使用二分查找算法来计算非负整数x的平方根的方法。首先尝试使用Java内置的Math.sqrt()函数,但实际问题是要返回整数部分。接着,通过二分查找策略解决这个问题,从1开始到x逐步缩小搜索范围,避免了大数值可能导致的溢出问题,最终找到最接近x平方根的整数值。
872

被折叠的 条评论
为什么被折叠?



