题目
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.
题目翻译:
给一个正整数,输出它的互补数,互补策略是使用它的二进制位翻转。
提示:
1.所给的正整数必须是32位的带有符号的整数。(拿着有道翻译的。。)
2.变成二进制后前面的零需要忽略不能取反。
给出的题目:(要求返回一个整数)
class Solution {
public:
int findComplement(int num) {
}
};
兴高采烈写了一个解法,最简单的思路:看num有几位,然后就2的几次方,得到的数-1-num就是答案,这里省略了位运算,但是运算时间极大的提升了,赶紧把答案放到网上跑一下,系统提示:您击败了2.8%的c++用户。。这就很尴尬了。必须得改啊。下面是劣质解法:
int findComplement(int num) {
int a = num,b=1;
while (a > 0)
{
b *= 2;
a /= 2;
}
return b-1-num;
}
int main()
{
cout << findComplement(5);
return 0;
}
经过网络借鉴。。找到了一个不错的思路
https://discuss.leetcode.com/topic/74627/3-line-c/3
int findComplement(int num) {
unsigned mask = ~0;
while (num & mask) mask<<=1;
return ~mask & ~num;
}
unsigned mask = ~0;得出1111 1111;(unsigned无符号)
while (num & mask) mask<<=1;1111 1111向左挪,挪的次数就是num的位数即只要还没遇到num二进制后最高位的1,就不会停下。
这里有两种return方法我直接思考到的是return ~(mask|num);,和上文方法意思基本一样。
嗨呀!这次就比较爽了,上网一跑,21%,还可以,希望大家能给我提点意见,有什么更快的方法能共享就更好了。