【LeetCode】476.Number Complement_EASY(二)

476.Number Complement

Description:
Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.

Note:
1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
2. 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.

以上是题目,因为例子解释得很清楚就不翻译题目内容了。

第一眼看这题,就想咋这么简单,取反操作不就完了,然后就gg了…
错误代码:

public class Solution {
    public int findComplement(int num) {
       return ~num;
    }
}

错误结果:
这里写图片描述

呵呵,大兄弟,你好像忘了int类型在java里是存储为补码形式的32位数了。

那就赶紧重新整理思路,其实取反操作是没啥问题,问题是要进行怎样的操作才能保证前导零不变的同时对其取反,容易想到以下两个与操作:
1. 输入数取反前的前导零位在取反后与“0”进行按位与操作;
2. 输入数取反前最左边的最高一位及其之后的位在取反后与“1”进行按位与操作;

即我们需要得到一个数,这个数取输入数的二进制形式最左边的最高一位且高位后面全部补“1”。
就得到如下代码:

public class Solution {
    public int findComplement(int num) {
       return ~num&((Integer.highestOneBit(num)<<1)-1);
    }
}

结果正确。
PS: highestOneBit(i):这个函数的作用是取 i 这个数的二进制形式最左边的最高一位且高位后面全部补零,最后返回int型的结果。

再进一步想,输入数最左边的最高位肯定是“1”,取反后为“0”,那进行与操作肯定是“0”,所以在这里我们可以把左移运算省略,即:

public class Solution {
    public int findComplement(int num) {
       return ~num&(Integer.highestOneBit(num)-1);
    }
}

完成。
还是一行代码的事儿……主要还是java的基础函数吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值