Number Complement – Leetcode

Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation.
Note:
  1. The given integer is guaranteed to fit within the range of a 32-bit signed integer.
  2. You could assume no leading zero bit in the integer’s binary representation.
Example 1:

Example 2:

 

Solution

If you have still not understood the solution, the below debugging will help you understand better.

Debug the solution

Output

You may also like Java interview questions

References
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#highestOneBit(int)
https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#toBinaryString(int)

Leave a Reply