Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đảo ngược bit trong C++


Cho số không dấu 32-bit x. Đảo ngược thứ tự các bit. Ví dụ: 00000000000000000000001001110100 → 00101110010000000000000000000000. Trả về số nguyên sau khi đảo bit.

Giải pháp

Các bước:

  • Khởi tạo ans = 0.
  • Với i từ 31 xuống 0: ans |= (n & 1) << i; n >>= 1.
  • Trả về ans.

Ví dụ

Triển khai C++:

#include <bits/stdc++.h> 
using namespace std; 
class Solution { 
public: 
    uint32_t reverseBits(uint32_t n) { 
        uint32_t ans = 0; 
        for(int i = 31; i >= 0; i--){ 
            ans |= (n & 1) <<i; 
            n>>=1; 
        } 
        return ans; 
    } 
}; 
main(){ 
    Solution ob; 
    cout << ob.reverseBits(0b00000000000000000000001001110100); 
}

Đầu vào

0b00000000000000000000001001110100

Đầu ra

775946240