LeetCode_Easy_471:Number Complement
2024-08-28 09:33:30
LeetCode_Easy_471:Number Complement
题目描述
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 101 (no leading zero bits), and its complement is 010. 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.
思路笔记
高效解
我能想到的直观思路,就是在二进制转十进制的时候将各位余数数值取反,然后再转换为十进制。
但是知道我看到了最优解:Java 1 line bit manipulation solution(仅仅一句话代码)
public int findComplement(int num) {
return ~num & ((Integer.highestOneBit(num) << 1) - 1);
}
收获:与非位运算
我们首先要理解位运算:
说明:
位运算包括:“与”、“非”、“或”、“异或”。
运算符主要针对两个二进制数的位进行逻辑运算。
非:
非运算符用符号“~”表示,其运算规律如下:
如果位为0,结果是1,如果位为1,结果是0,也就是每位都取反了。
public static void main(String[] args)
{
int a=2;
System.out.println("a 非的结果是:"+(~a));
}
在上述代码中:结果是 10 —> 01
与:
与运算符用符号“&”表示,其使用规律如下:
两个操作数中位都为1,结果才为1,否则结果为0
public static void main(String[] args)
{
int a=129;
int b=128;
System.out.println("a 和b 与的结果是:"+(a&b));
}在上述代码中:结果是 100101001&100101000—>100101000
然后我们总结一下一句话代码:
- 假设Num=5(101),我们求出其非值为(11111111111111111111111111111010)这是一个32位的值,可是我们只想要其后三位。
- Integer.highestOneBit(num) << 1) - 1,可以快速求出和其长度相同的且各位为1的值,即111。
- 两者求与,剩下的就是010。
最新文章
- Linux下FTP安装与配置
- javascript实现列表的点击展开折叠
- 拾遗:『Linux Capability』
- mongdb Java demo
- 详解强大的SQL注入工具——SQLMAP
- codevs 1220 数字三角形
- Tomcat 配置支持APR
- scala练手之数字转汉字小工具
- Android App 压力测试方法(Monkey)
- ZJOI 2014 星系调查(推导)
- Python-wxpy继承关系
- django中的中间件
- Python+Selenium笔记(十二):数据驱动测试
- lua总则
- node.js入门基础
- [算法]用java实现堆操作
- Mysql explain执行计划
- python经典书记必读:Python编程快速上手 让繁琐工作自动化
- 高可用Kubernetes集群-3. etcd高可用集群
- jmeter接口测试实战
热门文章
- linux学习之vimrc配置推荐
- Python内置函数之classmethod()
- Python内置函数之bool()
- CronTrigger中cron表达式使用
- 通过Java发射机制调用可变参数函数
- OpenCV中Kinect的使用(1)
- tcp/iP协议族——IP工作原理及实例具体解释(下)
- GoogleMap-------解决不能使用问题
- cvsba-1.0.0/utils/test_cvsba.cpp:.......error: ‘numeric_limits’ is not a member of ‘std’... error: expected primary-expression before ‘float’....
- linux下jmeter使用帮助