标签:
everse 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
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
将一个整形数的二进制序列逆转,后输出二进制序列代表的十进制数
采用一个32长度的数组,存储二进制,之后逆转,再计算此数组所表示的整形数。
class Solution { public: uint32_t reverseBits(uint32_t n) { vector<int> a(32,0); int mood=0,i=0,temp; unsigned int temp1=0; while(n/2!=0) { mood=n%2; a[i]=mood; n/=2; i++; } a[i]=n%2; reverse(a.begin(),a.end()); for(int j=0;j<32;j++) { if (a[j]!=0) { temp=pow(2*1.0,j); temp1+=temp; } } return temp1; } };
class Solution { public: uint32_t reverseBits(uint32_t n) { uint32_t bin=0; for (int i = 0; i < 32; i++) bin+=(n >> i & 1)<<(31-i); return bin; } };
标签:
原文地址:http://blog.csdn.net/sinat_24520925/article/details/45696175