LeetCode: 476. 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
1. 32-bit signed integer. You could assume no leading zero bit in the
2. integer’s binary representation.
public class Solution {
public int findComplement(int num) {
int length = (int) (Math.log(num) / Math.log(2)) + 1;
int mod = ~(0xffffffff << length);
return (~ num) & mod;
}
}