- 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:

- 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.

1 | Example 1: |

1 | Example 2: |

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

3 line C++

1 | class Solution { |

1 | For example, |

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.

1 | public class Solution { |

According to the problem, the result is

- The flipped version of the original input but
- 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:

- 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.
- Negate the whole input number.
- Bit AND numbers in step 1 and 2.

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

1 | public class Solution { |

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

Simple Python

使用cpp测试，会超时，可能是因为cpp整数32位，很容易超出范围。

1 | class Solution(object): |

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

maybe fewest operations

1 | int findComplement(int num) { |

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

1 | public int findComplement(int num) |

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

Oneline C++ Solution

1 | public: |