LeetCode *** 190. Reverse Bits

来源:互联网 发布:excel sql语法大全 编辑:程序博客网 时间:2024/05/18 02:00

题目:

Reverse bits of a given 32 bits unsigned integer.

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

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

Related problem: Reverse Integer

分析:

一开始习惯性写int,后来WA之后测试才发现应该写uint32_t,总之以后不能出现这种错误了。


代码:

class Solution {public:    uint32_t reverseBits(uint32_t n) {                uint32_t res=0;        uint32_t resTmp=pow(2,31);        while(n){            if(n%2)res+=resTmp;            n/=2;            resTmp/=2;        }        return res;    }};

0 0