Title description
Implement the function int sqrt (int x).
Calculate and return the square root of x
analysis
- The sum of squares can be reduced to a sequence by the concept of sequence.
- Find the first number in the sequence that is greater than x, and the subscript can be used to find the result.
java code
public class Solution {
public int sqrt(int x) {
if(x <= 0){
return 0;
}
//使用累加法 1 4 9 16 25 ****
//这些数的间隔是 3 5 7 9 ***
//间隔自增2
int res = 0;
int delta = 1;
int index = 0;
//找出第一个大于x的res和index
while(res <= x){
//如果x比较大 接近于 Integer.MAX_VALUE。
//sqrt(Integer.MAX_VALUE)^2 可能比Integer.MAX_VALUE小很多
//如果继续增量delta,会出现错误,而事实上,这些数x的解就已经算出来了
if(Integer.MAX_VALUE - res < delta){
return index ;
}
res += delta;
delta += 2;
index ++;
}
//出来循环的 一定是大于x的res
return index - 1;
}
}