LeetCode#476: Number Complement
阿新 • • 發佈:2018-11-19
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);
}
}