[Leetcode] 190. Reverse Bits 解题报告

来源:互联网 发布:龙神契约神通进阶数据 编辑:程序博客网 时间:2024/05/18 00:44

题目

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).

Follow up:
If this function is called many times, how would you optimize it?

Related problem: Reverse Integer

思路

也是一道easy级别的题目,算法方面没有什么难度,但我这里提供一个非常精简的代码片段:申请一个变量ret,然后每次让其左移1位,和n右移1位的结果进行或操作,这样每次就能得到n的最低位。四行代码就搞定了。

代码

class Solution {public:    uint32_t reverseBits(uint32_t n) {        uint32_t ret = 0;          for(int i = 0; i < 32; ++i)            ret = (ret << 1) | ( (n >> i) & 1);     // update rightmost bit        return ret;      }};

原创粉丝点击