class Solution {
fun mySqrt(x: Int): Int {
if (x < 2) return x
var left = 0
var right = x
while (left < right) {
val mid = (left + right) / 2
val x_long = x.toLong()
val square_long = mid.toLong() * mid
val square_plus_one_long = (mid + 1).toLong() * (mid + 1)
when {
x_long == square_long -> return mid
x_long > square_long -> {
if (square_plus_one_long > x_long) {
return mid
} else {
left = mid
}
}
else -> right = mid
}
}
return right
}
}