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.
public int findComplement(int num) {
int flag = 31;
int result = 0;
int re[] = new int[32];
for (int i = 0; i < 32; i++) {
re[i] = num % 2;
num = num / 2;
}
while (re[flag--] == 0)
;
for (++flag; flag >= 0; flag--)
if (re[flag] == 0)
re[flag] = 1;
else
re[flag] = 0;
for (int j = 0; j < 32; j++)
result += re[j] * (int) Math.pow(2, j);
return result;
}