이걸 다루는 문제는 처음이여서 정리
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift
Unsigned right shift (>>>) - JavaScript | MDN
The unsigned right shift operator (>>>) (zero-fill right shift) evaluates the left-hand operand as an unsigned number, and shifts the binary representation of that number by the number of bits, modulo 32, specified by the right-hand operand. Excess bits sh
developer.mozilla.org
Unsigned Integer in Javascript
https://leetcode.com/problems/reverse-bits/description/
Reverse Bits - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
부호 없는 long int 정의하기
let unsigned = someNum >>> 0
MDN에서 예시와 설명을 보면
>>>(right shift)는 왼쪽 피연산자를 부호 없는 숫자로 평가하고 해당 숫자의 이진 표현을 32만큼 이동함, 초과 비트는 제거
const a = 5; // 00000000000000000000000000000101
const b = 2; // 00000000000000000000000000000010
const c = -5; // 11111111111111111111111111111011
const d = 5; // 00000000000000000000000000000101
console.log(a >>> b); // 00000000000000000000000000000001
// expected output: 1
console.log(c >>> b); // 00111111111111111111111111111110
// expected output: 1073741822
*음수 양수 바꾸는거 -> 보수 : 모든 비트를 반전시킨후 1을 더하면 됨
9 (base 10): 00000000000000000000000000001001 (base 2)
--------------------------------
9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10)
양수일때 >> 와 >>>는 같은 결과를 나타내지만 음수로 가면
-9 (base 10): 11111111111111111111111111110111 (base 2)
--------------------------------
-9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10)
-9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10)
전혀 다른 결과값을 보여준다.
먼저, >>(Signed right shift)은 맨 왼쪽 비트의 복사본을 왼쪽으로 밀어 넣어서 오른쪽으로 이동하게함, 맨 오른쪽 비트 떨어지게 만듬 [! 부호 비트 유지]
>>>은 왼쪽에 0을 밀어넣고 제일 오른쪽의 값이 떨어져 나가도록 한다. [! 부호 비트 무시] 그래서 좌변의 피 연산자가 음수 일경우 결과에서 양수로 변하는 것
[풀이]
padStart를 사용해서 0을 앞쪽에 32만큼 밀어넣음
var reverseBits = function(n) {
// n은 32bit로 주어짐 -> 이걸 2진수로 변환
let binaryN=n.toString(2)
let ans=binaryN.padStart(32,'0').split('').reverse().join('')
return parseInt(ans,2)
};
'알고리즘(Algorithm)' 카테고리의 다른 글
프로그래머스 - 가장 가까운 글자 [JS] (0) | 2022.12.18 |
---|---|
프로그래머스 시저 암호 [JS] (0) | 2022.12.17 |
그래프 순회 (0) | 2022.09.10 |
그래프 (0) | 2022.08.31 |
해시 테이블(HASH TABLES) (0) | 2022.08.30 |