반응형
https://leetcode.com/problems/reverse-bits/description/
문제
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 integer type. They should not affect your implementation, as the integer's internal binary representation is the same, whether it is signed or unsigned.
- In Java, the compiler represents the signed integers using 2's complement notation. Therefore, in Example 2 above, the input represents the signed integer -3 and the output represents the signed integer -1073741825.
Example 1:
Input: n = 00000010100101000001111010011100
Output: 964176192 (00111001011110000010100101000000)
Explanation: The input binary string 00000010100101000001111010011100 represents the unsigned integer 43261596, so return 964176192 which its binary representation is 00111001011110000010100101000000.
Example 2:
Input: n = 11111111111111111111111111111101
Output: 3221225471 (10111111111111111111111111111111)
Explanation: The input binary string 11111111111111111111111111111101 represents the unsigned integer 4294967293, so return 3221225471 which its binary representation is 10111111111111111111111111111111.
Constraints:
- The input must be a binary string of length 32
풀이
풀이 과정
주어진 32비트 정수를 거꾸로 구하는 문제이다.
정답 변수 answer를 0으로 초기화하고 n 비트를 순회하며 다음의 과정을 반복한다.
- answer를 왼쪽 shift
- n의 마지막 비트( n과 1의 AND 연산)를 answer에 마지막에 추가 ( OR연산 )
- n 오른쪽 shift
최종 코드
public class Solution {
// you need treat n as an unsigned value
public int reverseBits(int n) {
int answer = 0;
for(int i = 0; i < 32; i++){
// 정답 비트를 왼쪽으로 한칸 이동
answer <<= 1;
// 현재 n의 맨 마지막 비트를 정답의 마지막에 추가
answer |= (n & 1);
// n의 비트를 오른쪽으로 한 칸 이동
n >>= 1;
}
return answer;
}
}
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 20. Valid Parentheses - Java (0) | 2022.12.01 |
---|---|
[LeetCode] 242. Valid Anagram - Java (0) | 2022.11.30 |
[LeetCode] 338. Counting Bits - Java (0) | 2022.11.22 |
[LeetCode] 191. Number of 1 Bits - Java (0) | 2022.11.22 |
[LeetCode] 371. Sum of Two Integers - Java (0) | 2022.11.21 |