Algolithm-Leetcode/Bit Manipulation
Reverse Bits
꿀잠마스터
2026. 8. 23. 21:08
https://leetcode.com/problems/reverse-bits/description/
Reverse Bits - LeetCode
Can you solve this real interview question? Reverse Bits - Reverse bits of a given 32 bits signed integer. Example 1: Input: n = 43261596 Output: 964176192 Explanation: Integer Binary 43261596 00000010100101000001111010011100 964176192 00111001011110000
leetcode.com
주어진 인트의 32비트 2진수 값을 순서를 반전 하였을 때 값을 리턴하는 문제이다.
StringBuilder 클래스의 reverse 메서드를 통해 문자열을 반전하기 쉬워 해당 메서드를 이용하여 해결하였다.
public class Solution {
public int reverseBits(int n) {
String from = Integer.toString(n, 2);
StringBuilder sb = new StringBuilder(from);
sb.reverse();
int needZero = 32 - sb.length();
for(int i = 0; i < needZero; i++){
sb.append('0');
}
return Integer.valueOf(sb.toString(), 2);
}
}
비트 연산자를 이용해 해결하고 싶다면 아래와 같은 방식으로 해결할 수 있다.
class Solution {
public int reverseBits(int n) {
int result = 0;
for (int i = 0; i < 32; i++) {
result = (result << 1) | (n & 1);
n >>>= 1;
}
return result;
}
}