[LeetCode] 3769. Sort Integers by Binary Reflection

Chobby·4일 전

LeetCode

목록 보기
960/969

😎풀이

  1. 특정 정수를 2진수로 변환한뒤 반대로 뒤집어 반환하는 헬퍼 함수 getBinaryReflection 정의
  2. nums를 정렬, getBinaryReflection된 결괏값 기준 오름차 순이며 동일할 경우 원래 정수의 숫자를 기준으로 오름차 순 정렬
function sortByReflection(nums: number[]): number[] {
    return nums.toSorted((a, b) => {
        const refA = getBinaryReflection(a)
        const refB = getBinaryReflection(b)
        if(refA !== refB) return refA - refB
        return a - b
    })
};

function getBinaryReflection(num: number) {
    const binary = num.toString(2)
    const reflected = [...binary].toReversed().join('')
    return parseInt(reflected, 2)
}
profile
내 지식을 공유할 수 있는 대담함

0개의 댓글