[勇者闯LeetCode] 190. Reverse Bits

来源:互联网 发布:apache listen 编辑:程序博客网 时间:2024/05/17 05:12

[勇者闯LeetCode] 190. Reverse Bits

Description

Reverse bits of a given 32 bits unsigned integer.

For example, given input 43261596 (represented in binary as 00000010100101000001111010011100), return 964176192 (represented in binary as 00111001011110000010100101000000).

Information

  • Tags: Bit Manipulation
  • Difficulty: Easy

Solution

result初值为0,32次循环:
每次result先左移一位,然后将n与1进行&操作取出n的最后一位,通过|操作放到result的最后一位上,n右移一位。

C++ Code

class Solution {public:    uint32_t reverseBits(uint32_t n) {        uint32_t result = 0;        int count = 32;        while (count--) {            result <<= 1;            result |= n & 1;            n >>= 1;        }        return result;    }};
原创粉丝点击