Number Complement:数字填充位操作
来源:互联网 发布:杭州移领网络怎么样 编辑:程序博客网 时间:2024/05/16 08:18
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.
思路:
朴素思路:按位判断,累加求和
class Solution { public static int findComplement(int num) { if(num == 0) return 1; int factor = 1; int result = 0; while(num>0){ if((num&1)==0){ result += factor; } factor = factor<<1; num = num>>1; } return result; }}思路二:求出和呆求数字一样长的全一数字,二者异或
int findComplement(int num) { int mask = num; mask |= mask >> 1; mask |= mask >> 2; mask |= mask >> 4; mask |= mask >> 8; mask |= mask >> 16; return num ^ mask;}有答案说使用highestOneBit(int i),实际上,其源码是:
/** * Returns an {@code int} value with at most a single one-bit, in the * position of the highest-order ("leftmost") one-bit in the specified * {@code int} value. Returns zero if the specified value has no * one-bits in its two's complement binary representation, that is, if it * is equal to zero. * * @return an {@code int} value with a single one-bit, in the position * of the highest-order one-bit in the specified value, or zero if * the specified value is itself equal to zero. * @since 1.5 */ public static int highestOneBit(int i) { // HD, Figure 3-1 i |= (i >> 1); i |= (i >> 2); i |= (i >> 4); i |= (i >> 8); i |= (i >> 16); return i - (i >>> 1); }实际上和思路二本质相同。
阅读全文
0 0
- Number Complement:数字填充位操作
- LeetCode476. Number Complement位操作面试题
- 位操作-leetcode 476. Number Complement
- (leetcode)位运算 Number Complement
- LeetCode 476 Number Complement(位运算)
- Leetcode-Algorithms Number Complement(数字补码)
- [LeetCode]476. Number Complement(数字补码)
- LeetCode 简单操作 | 476. Number Complement
- Number Complement
- Number Complement
- Number Complement
- Number Complement
- Number Complement
- Number Complement
- Number Complement
- Number Complement
- Number Complement
- Number Complement
- 数据库范式
- 本周六下午北京Linuxer聚会下午茶、交流欢迎报名参加(更新)
- postgresql时区问题,系统时间和pg时间不一致
- Android 讯飞语音知识点(BNF与ABNF与错误码列表)
- 人情冷暖,饮水自知
- Number Complement:数字填充位操作
- 属性动画制作
- 快捷操作
- 构建需求响应式亿级商品详情页
- 深度学习的开源Java ML框架
- 习题4.2
- 海航王健是这样带领三亚机场获国际大奖的
- ckeckbox全选/反选
- 微信公众号 授权登录 JAVA