Skip to content

E190.颠倒二进制位

bit manipulation, https://leetcode.cn/problems/reverse-bits/

cpp
class Solution {
public:
    int reverseBits(int n) {
        unsigned int ori = n, ans = 0;
        for (int i = 0; i < 32; i++) {
            ans = (ans << 1) | (ori & 1);
            ori >>= 1;
        }
        return static_cast<int>(ans);
    }
};

思路:简单的位运算

cpp
#include <bits/stdc++.h>
using namespace std;

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

用时5min