LeetCode#476: Number Complement

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38283262/article/details/84197071

Description

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

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.
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.

Solution

我们先使用Integer.highestOneBit方法得到数字的二进制的最高位,例如,对于二进制00000000 01100011通过这个方法将会得到00000000 01000000,将其左移并减一得到00000000 01111111,这串掩码可以用来消除开头的0待会取反码转成1的位。然后我们将原数字取反码得到11111111 10011100,再与刚才的掩码相与便得到舍弃了不必要的高位取反的最终答案00000000 00011100

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

猜你喜欢

转载自blog.csdn.net/qq_38283262/article/details/84197071