[LeetCode] 374. Guess Number Higher or Lower(Kotlin)

0

LeetCode

목록 보기
24/58
post-thumbnail

[LeetCode] 374. Guess Number Higher or Lower(Kotlin)

풀이

  • 이분 탐색 알고리즘
/** 
 * The API guess is defined in the parent class.
 * @param  num   your guess
 * @return 	     -1 if num is higher than the picked number
 *			      1 if num is lower than the picked number
 *               otherwise return 0
 * fun guess(num:Int):Int {}
 */

class Solution:GuessGame() {
    override fun guessNumber(n:Int):Int {
        var maxGuess:Long = n.toLong()
        var minGuess:Long = 1L

        var curGuess:Long = -1L
        while(true){
            curGuess = (maxGuess + minGuess)/2L
            println("curGuess: $curGuess")
            when(guess(curGuess.toInt())){
                0 -> return curGuess.toInt()
                -1 -> maxGuess = curGuess
                1 -> minGuess = curGuess + 1
            }
        }
        return -1
    }
}
profile
Be able to be vulnerable, in search of truth

0개의 댓글