Thought:
It is a Binary Search.
Code:
public class Solution {
public int sqrt(int x) {
if (x == 0) return 0;
int result = 2;
int tmp = 1;
while ( !(result <= x/result && result + 1 > x/(result + 1)) ) {
if (result < x/result) {
tmp = result;
result = result * result;
}else {
result = (result + tmp) / 2;
}
}
return result;
}
}
No comments:
Post a Comment