프로그래밍/알고리즘

[LeetCode] 190. Reverse Bits

노란구슬 2026. 6. 3. 21:35
728x90
반응형

190. Reverse Bits

LeetCode

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

 

Reverse bits of a given 32 bits signed integer.

주어진 32비트 부호 있는 정수(signed integer)의 비트를 뒤집으세요.

 

Example

Input: n = 43261596
Output: 964176192
Input: n = 2147483644
Output: 1073741822

1. 문제 요구사항 분석

32개의 비트 칸을 통째로 좌우 반전시키는 작업

2. 접근 전략

😁 비트 하나씩 옮기기

1. 비트 옮기기 n & 1

2. result << 1 : 왼쪽으로 한 칸 밀기

3. 해당 칸에 비트 넣기 (n & 1 한 값을 왼쪽으로 민 칸에 넣기)

3. 다음 비트 준비하기 (>>> 오른쪽으로 한칸 밀기)

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;
    }
}
728x90
반응형

'프로그래밍 > 알고리즘' 카테고리의 다른 글

[LeetCode] 226. Invert Binary Tree  (0) 2026.06.10
[LeetCode] 242. Valid Anagram  (0) 2026.06.09
[LeetCode] 56. Merge Intervals  (0) 2026.06.01
[LeetCode] 268. Missing Number  (0) 2026.05.28
[LeetCode] 100. Same Tree  (0) 2026.05.27