最開始想到的是先把無符號數n轉換成二進制,然後把每一位依次存放到vector容器中,最後在以相反的順序取出每一位的值換成十進制即可。代碼如下:
class Solution {
public:
uint32_t reverseBits(uint32_t n) {
int i = 0, index = 0;
vector<int> v;
//auto it = v.begin();
unsigned int res = 0;
if (n == 0)
return 0;
while (i < 32)
{
v.push_back(n % 2);
n /= 2;
i++;
}
for (auto it = v.rbegin(); it != v.rend(); it++)
res += *it * pow(2, index++);
return res;
}
};
然後看到Discuss中的用位運算來解決的,只用了4ms。比上面的方法簡潔也快速了很多。代碼如下:
uint32_t result = 0;
int bit = 0;
for(int i=0; i<32; i++)
{
bit = n&1;
n = n>>1;
result = 2*result + bit;
}
return result;
因爲除2操作就相當於右移一位,從最低位開始,如果該位爲1,result += pow(2,32-該位的位置)。