当前位置: 首页 > news >正文

位运算进阶操作

位运算的进阶操作,适合做题的时候用,共10点

1.通过位运算与特定的位模式进行掩码操作,可以提取、设置或清除特定的位信息。例如,我们可以使用位掩码来检查一个数的二进制表示中特定位置是否为1。

bool checkBit(int num, int position) {int mask = 1 << position;return ((num & mask) != 0);
}

2.位运算交换值,无需使用额外的变量

void bitwiseSwap(int& a, int& b) {a = a ^ b;b = a ^ b;a = a ^ b;
}

3.位运算计数,可以快速计算整数的二进制表示中有多少个位为1。

int countBits(int num) {int count = 0;while (num != 0) {count += num & 1;num >>= 1;}return count;
}

4.位运算生成全排列

void generatePermutations(int n) {// 生成0到2^n-1的所有整数for (int i = 0; i < (1 << n); ++i) {// 对每个整数,输出选择的位for (int j = 0; j < n; ++j) {if (i & (1 << j)) {cout << j << " ";}}cout << endl;}
}

5.位运算快速幂运算,时间复杂度为O(logn) n为指数

int fastPower(int base, int exponent) {int result = 1;while (exponent > 0) {if (exponent & 1) {result *= base;}base *= base;exponent >>= 1;}return result;
}

6.位运算判断是否为2的幂

bool isPowerOfTwo(int num) {return (num != 0) && ((num & (num - 1)) == 0);
}

7.位运算求补集

int bitwiseComplement(int num) {unsigned int mask = 1;while (mask < num) {mask = (mask << 1) + 1;}return num ^ mask;
}

8.位运算统计不同位数,以快速统计两个整数的二进制表示中不同的位数

int countDifferentBits(int num1, int num2) {int count = 0;int diff = num1 ^ num2;while (diff != 0) {count += diff & 1;diff >>= 1;}return count;
}

9.位运算获取最右边的1

int getRightmostOne(int num) {return num & -num;
}

10.位运算交换二进制奇偶位

int swapOddEvenBits(int num) {unsigned int evenBits = num & 0xaaaaaaaa;  // 1010...unsigned int oddBits = num & 0x55555555;   // 0101...evenBits >>= 1;oddBits <<= 1;return evenBits | oddBits;
}

http://www.lryc.cn/news/147587.html

相关文章:

  • sql:SQL优化知识点记录(四)
  • Java----Sentinel持久化规则启动
  • Java版工程行业管理系统源码-专业的工程管理软件- 工程项目各模块及其功能点清单
  • 无涯教程-Android - Grid View函数
  • 【第四阶段】kotlin语言的解构语法过滤元素
  • 和24考研说拜拜,不考研读中外合作办学硕士——人大女王金融硕士
  • https比http安全在哪
  • 基于Java的代驾管理系统 springboot+vue,mysql数据库,前台用户、商户+后台管理员,有一万五千字报告,完美运行
  • 广播、组播
  • Spring MVC 三 :基于注解配置
  • 机器学习基础16-建立预测模型项目模板
  • ReID网络:MGN网络(4) - Loss计算
  • CountDownLatch、Semaphore详解——深入探究CountDownLatch、Semaphore源码
  • windows生成ios证书的方法
  • 【小沐学Unity3d】3ds Max 骨骼动画制作(Physique 修改器)
  • 生态项目|Typus如何用Sui特性制作动态NFT为DeFi赋能
  • IOS打包上架AppStore被驳回信息记录
  • 【Python自学笔记】Python好用的模块收集(持续更新...)
  • 在springboot中配置mybatis(mybatis-plus)mapper.xml扫描路径的问题
  • c++搜索剪枝常见方法与技巧
  • YOLO V5 和 YOLO V8 对比学习
  • 【Git】(六)子模块跟随主仓库切换分支
  • 开源的经济影响:商业与社区的平衡
  • 数据库复习整理
  • 开始MySQL之路——MySQL安装和卸载
  • pxe网络装机
  • 【数据库事务】
  • Apache Tomcat
  • python类
  • SpringBoot + layui 框架实现一周免登陆功能