Recca Chao 的 gitHub page

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

View on GitHub

Kotlin Leetcode - 69. Sqrt(x)

題目連接: https://leetcode.com/problems/sqrtx/

class Solution {
    fun mySqrt(x: Int): Int {
    }
}

解題思路

這題考驗的是會不會實作 binary search

Kotlin 參考解答

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
    }
}

回到 leetcode 列表