LeetCode 1356. Sort Integers by The Number of 1 Bits in F#

URL

Sort Integers by The Number of 1 Bits - LeetCode

Code

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

let sortByBits (arr: int list) : int list =
    let popCount n =
        let n = (n &&& 0x55555555) + ((n >>> 1) &&& 0x55555555)
        let n = (n &&& 0x33333333) + ((n >>> 2) &&& 0x33333333)
        let n = (n &&& 0x0F0F0F0F) + ((n >>> 4) &&& 0x0F0F0F0F)
        let n = (n &&& 0x00FF00FF) + ((n >>> 8) &&& 0x00FF00FF)
        (n &&& 0x0000FFFF) + ((n >>> 16) &&& 0x0000FFFF)

    arr
    |> List.map (fun n -> n, popCount n)
    |> List.sortWith (fun (a1, b1) (a2, b2) -> if b1 = b2 then compare a1 a2 else compare b1 b2)
    |> List.map fst