Recca Chao 的 gitHub page

推廣網站開發,包含 Laravel 和 Kotlin 後端撰寫、自動化測試、讀書心得等。Taiwan Kotlin User Group 管理員。

View on GitHub
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
    }
}