190顛倒二進制位(位運算+分治思想)

1、題目描述

顛倒給定的 32 位無符號整數的二進制位。

2、示例

輸入: 00000010100101000001111010011100
輸出: 00111001011110000010100101000000
解釋: 輸入的二進制串 00000010100101000001111010011100 表示無符號整數 43261596,
     因此返回 964176192,其二進制表示形式爲 00111001011110000010100101000000。

3、題解

解法一:

基本思想:位運算+分治思想,將32位分爲高低交換,對半重複操作,不斷重複,直至相鄰每一位互換,面試可能問到,要求不使用循環實現,時間複雜度O(1)空間複雜度O(1)

解法二:

基本思想:位運算,時間複雜度O(32)空間複雜度O(1)

#include<iostream>
#include<vector>
#include<deque>
#include<bitset>
#include<algorithm>
using namespace std;
class Solution {
public:
	uint32_t reverseBits(uint32_t n) {
		//基本思想:位運算+分治思想,將32位分爲高低交換,對半重複操作,不斷重複,直至相鄰每一位互換
		//面試可能問到,要求不使用循環實現
		n = ((n & 0xffff0000) >> 16) | ((n & 0x0000ffff) << 16);
		n = ((n & 0xff00ff00) >> 8) | ((n & 0x00ff00ff) << 8);
		n = ((n & 0xf0f0f0f0) >> 4) | ((n & 0x0f0f0f0f) << 4);
		n = ((n & 0xcccccccc) >> 2) | ((n & 0x33333333) << 2);
		n = ((n & 0xaaaaaaaa) >> 1) | ((n & 0x55555555) << 1);
		return n;
	}
};
class Solution1 {
public:
	uint32_t reverseBits(uint32_t n) {
		//基本思想:位運算,時間複雜度O(32)空間複雜度O(1)
		uint32_t res = 0;
		int power = 31;
		while (n != 0)
		{
			//計算n最低位是0還是1,然後左移對稱的位數就是翻轉後對應的值,也可以n%2
			res += (n & 1) << power;
			n >>= 1;
			power--;
		}
		return res;
	}
};
int main()
{
	Solution solute;
	uint32_t n = 4294967293;
	cout << solute.reverseBits(n) << endl;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章