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.提意:
给一个[-1000,1000]区间内的数,对它二进制的数求反然后输出
思路:
输入:num
求反:因为是二进制的操作,所以就想到什么位运算(^)、与运算(&)、左移(<<)右移(>>)这些东西
举例子101取反就是010,110取反就是001,100取反就是011
位运算的规则是相同的取0,不同的取1
那么101和111进行位运算得出的就是010,110和111的结果是001,100和111位运算的结果就是011
下一步就是想怎么找到和num位数相同的111
看了眼答案,discuss给出的结果就是for(i=1;i<=num;i*=2) num^=i;
也就是说,在i=1,2,4,8,16,32....的时候 循环和num进行位运算,也就是i=1,10,100,1000,1000
很好,正好可以和num的位数相同,只不过是一位一位的进行位运算
输出:num
int findComplement(int num) {
//int num=0;
long i=1;
for(i=1;i<=num;i*=2){
num^=i;
}
return num;
}
tips:
1.因为num有正有负,所以i变成long型
2.for(i=1;i<=num;i*=2) 里面的i*=2不能写成i*2....我也不知道为什么