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 32-bit signed integer.
You could assume no leading zero bit in the integer’s binary representation.
Example 1:
Example 2:
Complexity: O(1) time, O(1) space
The Idea: First we find the first maximum significant bit. We do this by simply shifting 1 to the maximum bit location (30) (side note: 31 is reserved as the complement). Then we continue to shift this number to the right by 1 until it reaches the first 1. Then using MAX_INT
, we can obtain all 1's and shift these to the right until we obtain the maximum significant digit that we found. Finally, xor
'ing this number with the result toggles everything.
Last updated