(yes, this is a leetCode problem)
the problem: 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.
Note: You are not allowed to use any built-in exponent function or operator, such as pow(x, 0.5) or x ** 0.5.
my solution:
class Solution {
fun mySqrt(x: Int): Int {
var start = 1
var end = x
var ans = 0
while (start <= end) {
val mid = (start + end) / 2
if(mid*mid < x) {
start = mid + 1
ans = mid
} else if(mid*mid>x) {
end = mid - 1
} else {
return mid
}
}
return ans
}
}
which is based on the binary search algorithm, buuuut it exceeds the time limit, how can I optimise this?