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;
}
}
'Algolithm-Leetcode > Bit Manipulation' 카테고리의 다른 글
| Sum of Two Integers (0) | 2026.09.04 |
|---|---|
| Counting Bits (0) | 2026.08.19 |
| Number of 1 Bits (0) | 2026.08.13 |
| Single Number (0) | 2026.08.07 |