【LeetCode】476. Number Complement (java实现)
来源:互联网 发布:基金推荐知乎 编辑:程序博客网 时间:2024/05/17 00:15
原题链接
https://leetcode.com/problems/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: 5Output: 2Explanation: 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: 1Output: 0Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
题目要求
题目要求为:给定一个非负整数,求出其complement number。所谓complement number,指对整数二进制最高位为1的位之后的所有位置取反,如5的二进制表示为00……00101,起最高位为1的位置是3,因此只对3之后的所有位置取反,得到00*00010,最后得出complement number为2。
解法
解法一:先求出最高位为1的位数,然后计算出掩码,再将原数据取反后和掩码求与,即得出最后结果。
public int findComplement(int num) { int valid = 0; // 最高位为1的位数 int tmp = num; while(tmp > 0) { tmp /= 2; valid++; } return ~num & ((1 << valid) - 1);}
其中,(1 << valid) - 1是二进制操作中一种常用的求掩码的方式,如valid为3,那么1<
public int findComplement(int num) { return ~num & ((Integer.highestOneBit(num) << 1) - 1);}
测试用例:
public static void main(String[] args) { Solution s = new Solution(); assert(s.findComplement(5) == 2); assert(s.findComplement(1) == 0); assert(s.findComplement(0) == 0);}
0 0
- 【LeetCode】476. Number Complement (java实现)
- LeetCode 476. Number Complement(Java)
- LeetCode 476. Number Complement-Java
- leetcode oj java 476. Number Complement
- LeetCode 476. Number Complement
- leetcode 476. Number Complement
- 【Leetcode】476. Number Complement
- 【Leetcode】476. Number Complement
- LeetCode 476. Number Complement
- LeetCode 476. Number Complement
- LeetCode--476. Number Complement
- LeetCode 476. Number Complement
- 476. Number Complement [LeetCode]
- [LeetCode]476.Number Complement
- 【LeetCode】 476. Number Complement
- LeetCode 476. Number Complement
- LeetCode 476. Number Complement
- 【LeetCode】476. Number Complement
- 三星公布Note 7燃损调查结果总结经验教训强化安全措施
- 三星事件背后真相公布 吸取教训为未来产品安全护航
- Hdu1170 Balloon Comes!
- 谷歌十诫
- 一起talk C栗子吧(第一百九十八回:C语言实例--DIY cp命令二)
- 【LeetCode】476. Number Complement (java实现)
- 三星公布Note7燃损原因 不惜成本历经数月调查揪出电池“元凶”
- Leetcode 20. Valid Parentheses
- RGraph 系列文章(一):如何安装RGraph
- Mac / Linux 环境下安装wget 出现Error错误
- Leetcode 21. Merge Two Sorted Lists
- vc 支持通配符的文件删除
- (三)整数表示
- 三星公布Note7燃损原因 并将加强安全措施