标签:
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
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
Bit Manipulation
这道题目的意思是将一个32位字节存储的一个数,在二进制上前后旋转,然后得到一个新的二进制数,再将二进制数转换成unsigned long型的数输出
所以这道题用C++做的话很简单,主要是考虑bitset的使用(初始化和使用函数to_ulong)
#include<iostream> #include <bitset> using namespace std; typedef unsigned long uint32_t; uint32_t reverseBits(uint32_t n) { uint32_t result; //unsigned long val=n; int val=n; bitset<32>bit_temp(val); for(int i=0;i<16;i++) { bool temp; temp=bit_temp[i]; bit_temp[i]=bit_temp[31-i]; bit_temp[31-i]=temp; } result=bit_temp.to_ulong(); return result; } int main() { //cout<<reverseBits(1)<<endl; unsigned long a=12; cout<<sizeof(unsigned long)<<endl; cout<<sizeof(int)<<endl; cout<<sizeof(long)<<endl; bitset<32> temp(a); }
leetcode_190题——Reverse Bits(bitset的使用)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4470739.html