位运算(6)——Number Complement
2024-10-12 10:33:13
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
- The given integer is guaranteed to fit within the range of a 32-bit signed integer.
- You could assume no leading zero bit in the integer’s binary representation.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is (no leading zero bits), and its complement is . So you need to output 2.Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
public class Solution {
public int findComplement(int num) {
int mask = (Integer.highestOneBit(num) << 1) - 1;
num = ~num;
return num & mask;
}
}
Integer.highestOneBit(num); //01101返回1000,001返回1,101返回100
为什么需要mask:
例如num = 0000 1010,那么 ~num = 1111 0101,加入mask = 0000 1111后,~num前面的1都消除了。
最新文章
- mac下安装mysql教程
- 一款简洁大气的jquery日期日历插件
- NGUI 使用EventDelegate.Add与UIInput.onSubmit、UIInput.onChange限定编辑框中的内容
- 利用反射实现类通用的DAO层
- MAC电脑操作快捷键
- Less/Sass编译工具,koala使用指南
- 通知栏Notification的学习
- 用Get-ADComputer取非常用属性的值
- 初识 Asp.Net内置对象之Cookie对象
- 低压差稳压器AMS1585
- UVa 10020 - Minimal coverage(区间覆盖并贪心)
- java提高篇(五)-----使用序列化实现对象的拷贝
- HDU 4329 MAP(stringstream的用法)
- leetcode day8
- When Startup Disk is Full
- oldboy s21day15模块装饰器及其他应用
- 跨源资源共享(CORS)概念、实现(用Spring)、起源介绍
- 【题解】 bzoj3894: 文理分科 (网络流/最小割)
- java重新学习记载的一些资料。
- Snip for Mac(桌面截图工具)安装