题目名称
Reverse Bits—LeetCode链接
描述
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?
分析
这道题涉及到十进制数和二进制数的相互转换,无论是什么进制的数,都是一样的处理,我这里用了一个vector容器,存储一个十进制数转换成32位二进制的各个位,正好将二进制的reverse位存储在vector中,最终实现。
C++代码
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
if(n==0)
return 0;
uint32_t res=0;
vector<int> bits;
//倒序存储转换后的二进制数的各个位
while(n>0){
bits.push_back(n%2);
n /= 2;
}
//当不满32位时,补0
while(bits.size()<32)
bits.push_back(0);
vector<int>::iterator iter=bits.begin();
while(*iter==0)
iter++;
for(iter;iter!=bits.end()-1;iter++){
res = (res + *iter)*2;
}
res +=*(bits.end()-1);
cout<<res<<endl;
return res;
}
};
总结
这道题其实用数组会更方便一点,而且时间复杂度也会降低,直接定义一个32位的数组,由于这段时间一直在用容器都忘记数组这种更方便的数据结构了,大家可以自行尝试一下。