Reverse Bits

来源:互联网 发布:数字滚动抽奖软件 编辑:程序博客网 时间:2024/06/07 23:37

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

主要思路:

取出数字的最后一位,然后进行左移,移动到相应的位置,主要是吧各个移动的位数进行叠加到一起,用位运算|,

移动的位置要判断好。

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

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

#include<iostream>#include<algorithm>using namespace std;int reversenum(int n);int main(){int a[] = { 4, 5, 7, 8, 9, 22, 4, 56, 57 };for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)cout << reversenum(a[i]) << endl;system("pause");return 0;}int reversenum(int n){int result = 0;for (int i = 0; i < 32; i++){int temp = (n >> i) & 1;result |= (temp << (31 - i));}return result;}


0 0
原创粉丝点击