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;
}

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值