[LeetCode] Reverse Bits

아르당·2025년 10월 8일

LeetCode

목록 보기
43/68
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

주어진 32비트 정수를 뒤집어라.

Example

#1
Input: n = 43261596
Output: 964176192

IntegerBinary
4326159600000010100101000001111010011100
96417619200111001011110000010100101000000

#2
Input: n = 2147483644
Output: 1073741822

IntegerBinary
214748364401111111111111111111111111111100
107374182200111111111111111111111111111110

Constraints

  • 0 <= n <= 21^31 - 2
  • n은 짝수이다.

Solved

class Solution {
    public int reverseBits(int n) {
        int result = 0;
        
        for(int i = 0; i < 32; i++){
            int bit = n & 1;
            result = (result << 1) | bit;
            n = n >>> 1;
        }

        return result;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글