Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 374. Guess Number Higher or Lower in F#

Shohei Yoshida's photo
Shohei Yoshida
·Nov 16, 2022·

1 min read

URL

leetcode.com/problems/guess-number-higher-o..

Code

github.com/syohex/dotnet-study/blob/master/..

let mutable picked = 0

let guess (n: int) : int =
    if n > picked then -1
    elif n = picked then 0
    else 1

let guessNumber (n: int) : int =
    let rec guessNumber' left right =
        let mid = left + ((right - left) / 2)

        match guess mid with
        | 0 -> mid
        | -1 -> guessNumber' left (mid - 1)
        | 1 -> guessNumber' (mid + 1) right
        | _ -> failwith "never reach here"

    guessNumber' 1 n
 
Share this