NumberComplementOPT [source code]
public class NumberComplementOPT {
public int findComplement(int num) {
int mask = ~0;
while ((num & mask) > 0) mask <<=1;
return ~mask & ~num;
}
}
代码模板:
class Solution {
public:
int findComplement(int num) {
unsigned mask = ~0;
while (num & mask) mask <<= 1;
return ~mask & ~num;
}
};
For example,
num = 00000101
mask = 11111000
~mask & ~num = 00000010
这个算法总体还是不难理解的, 跟我本来的算法其实很类似;
用 JAVA 的写法大概实现了一下, 最后其实跑了17ms, 比普通的那个数完 #bit 之后的算法还要慢很多;
另外其实不是很理解这里的这个~在 JAVA 里面具体是怎么运行的;, 比如 repl 上面跑了一下, ~0是-1, ~5是-6;
大概查了一下 wiki ,好像理解这个问题了;
Problem 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.
Example 1:
Input: 5
Output: 2
Explanation: The binary representation of 5 is 101 (no leading zero bits), and its complement is 010. So you need to output 2.
Example 2:
Input: 1
Output: 0
Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
Bit Manipulation