#include <iostream>#include <stdio.h>#include <vector>#include <string>#include <bitset>using namespace std;/*问题: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分析:对给定的无符号32位整数的bit位进行逆置。提供的是无符号整数,如果最后一位为1,那么逆置后1被放到最高位是否要做特殊处理。如果不需要处理,直接用bitset即可,最后转化为unsigned-1=-(1)=-(000000000...1)=111111111...1=2^0 + ... + 2^31=2^32-1=4294967295输入:4326159610-1输出:964176192214748364804294967295关键:1 leecode中bitset不支持at函数,需要用[]*/typedef unsigned uint32_t;class Solution {public: uint32_t reverseBits(uint32_t n) { bitset<32> bits(n);//用数n初始化bit数组 int size = bits.size(); for(int i = 0 ; i < 16; i++) { int temp = bits[i]; bits[i] = bits[size - i - 1]; bits[size - i - 1] = temp; } unsigned result = 0; for(int i = 0 ; i < size ; i++) { result |= (bits[i] << i); } return result; }};void print(vector<int>& result){ if(result.empty()) { cout << "no result" << endl; return; } int size = result.size(); for(int i = 0 ; i < size ; i++) { cout << result.at(i) << " " ; } cout << endl;}void process(){ vector<int> nums; uint32_t num; Solution solution; while(cin >> num ) { uint32_t result = solution.reverseBits(num); cout << result << endl; }}int main(int argc , char* argv[]){ process(); getchar(); return 0;}
新闻热点
疑难解答