• 61.1%

https://leetcode.com/problems/number-complement/?tab=Description

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.

https://discuss.leetcode.com/topic/74627/3-line-c

3 line C++

https://discuss.leetcode.com/topic/74642/java-1-line-bit-manipulation-solution

Java 1 line bit manipulation solution

I post solution first and then give out explanation. Please think why does it work before read my explanation.

According to the problem, the result is

1. The flipped version of the original input but
2. Only flip N bits within the range from LEFTMOST bit of 1 to RIGHTMOST.

For example input = 5 (the binary representation is 101), the LEFTMOST bit of 1 is the third one from RIGHTMOST (100, N = 3). Then we need to flip 3 bits from RIGHTMOST and the answer is 010

To achieve above algorithm, we need to do 3 steps:

1. Create a bit mask which has N bits of 1 from RIGHTMOST. In above example, the mask is 111. And we can use the decent Java built-in function Integer.highestOneBit to get the LEFTMOST bit of 1, left shift one, and then minus one. Please remember this wonderful trick to create bit masks with N ones at RIGHTMOST, you will be able to use it later.
2. Negate the whole input number.
3. Bit AND numbers in step 1 and 2.

Three line solution if you think one line solution is too confusing:

https://discuss.leetcode.com/topic/74611/simple-python

Simple Python

https://discuss.leetcode.com/topic/74897/maybe-fewest-operations

maybe fewest operations

https://discuss.leetcode.com/topic/75605/java-very-simple-code-and-self-evident-explanation

Java, very simple code and self-evident, explanation

for example:

100110, its complement is 011001, the sum is 111111. So we only need get the min number large or equal to num, then do substraction

https://discuss.leetcode.com/topic/74570/oneline-c-solution

Oneline C++ Solution