Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 967. Numbers With Same Consecutive Differences in F#

Shohei Yoshida's photo
Shohei Yoshida
·Sep 3, 2022·

1 min read

URL

leetcode.com/problems/numbers-with-same-con..

Code

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

let numsSameConsecDiff (n: int) (k: int) : int list =
    let rec numsSameConsecDiff' num i n k acc =
        if i = n then
            num :: acc
        else
            let digit = num % 10

            let acc' =
                if digit - k >= 0 then
                    numsSameConsecDiff' ((num * 10) + (digit - k)) (i + 1) n k acc
                else
                    acc

            if k <> 0 && digit + k <= 9 then
                numsSameConsecDiff' ((num * 10) + (digit + k)) (i + 1) n k acc'
            else
                acc'

    seq { 1 .. 9 }
    |> Seq.fold (fun acc i -> numsSameConsecDiff' i 1 n k acc) []
    |> List.sort
 
Share this