LeetCode 3011. Find if Array Can Be Sorted in F#

URL

Find if Array Can Be Sorted - LeetCode

Code

https://github.com/syohex/dotnet-study/tree/master/fsharp/leetcode/challenge/202411/find_if_array_can_be_sorted/main.fsx

let canSortArray (nums: int list) : bool =
    let rec countBits n acc =
        if n = 0 then acc else countBits (n >>> 1) (acc + (n &&& 1))

    let sorted = List.sort nums
    // use Seq.sort to use stable sort
    let bitSorted =
        nums
        |> List.map (fun n -> n, countBits n 0)
        |> Seq.sortWith (fun (a, ones1) (b, ones2) -> if ones1 = ones2 then compare a b else 0)
        |> Seq.map fst
        |> Seq.toList

    sorted = bitSorted