https://leetcode.com/problems/reverse-bits/
Reverse Bits - LeetCode
Can you solve this real interview question? Reverse Bits - Reverse bits of a given 32 bits unsigned integer. Note: * Note that in some languages, such as Java, there is no unsigned integer type. In this case, both input and output will be given as a signed
leetcode.com
Reverse Bits - 비트 뒤집기
Reverse bits of a given 32 bits unsigned integer.
32비트 무부호 정수를 뒤집어라.
풀이
1) toString(2)와 parseInt(x, 2) 같은 빌트인 메서드를 사용하면
32 길이의 문자열을 다 담아낼 수 없기에 bit mask를 써서 한 땀 한 땀 처리해야 한다.
&과 |를 사용하면 풀 수 있는데,
0101을 뒤집는다 가정하면,
맨 오른쪽부터 시작해서 1의 유무를 체크한다.
0101
1을 발견했기에 이를 bit라는 변수로 선언하면 현재 bit는 1이다.
이 걸 왼쪽에서부터 시작해서 채워 넣어야 하는데,
문자열의 길이보다 1 작은 3만큼 bit를 << 이동시키면
1000이 된다.
이를 0인 result인 변수에 | 하면 1000이 되는데 이를 처음부터 끝까지 반복하면
1010으로 만들 수 있다.
코드를 보면 이해가 더 쉬울 수 있다.
코드
마지막에 result >>> 0를 하는 이유는
자바스크립트에는 unsigned, signed가 구분이 되어있는데
>>나 <<를 사용하면 signed가 되지만
마지막 리턴시에 >>> 0을 쓰게 되면 unsigned로 전환되기 때문에 저렇게 작성했다.
자바스크립트에는 unsigned 전용 shift인 >>>는 있지만 <<는 없어서 강제적으로 signed를 사용할 수밖에 없었다.
비트 오퍼레이션은 거의 연습을 안 했어서 간단한 문제이지만 무진장 헷갈린다.
'Blind 75 > Bit Manipulation' 카테고리의 다른 글
Blind 75 | Missing Number (Bit Manipulation 4 / 5) (0) | 2023.06.12 |
---|---|
Blind 75 | Counting Bits (Bit Manipulation 2 / 5) (0) | 2023.06.12 |
Blind 75 | Number of 1 Bits (Bit Manipulation 1 / 5) (0) | 2023.06.12 |