题目
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.
题目大意
给定一个正数,输出能补全这个数的数。也就是说,比如你输入5,它的二进制表示是101,要“补全”就是让每一个0位变成1,因此补全的数为2.
解题思路
找到所给数对应的所有二进制位全为一的数,然后减去自身就可以得到。
代码如下:
class Solution {
public int findComplement(int num){
int mark=0;
for(int i=0;i<num;i++){
if(Math.pow(2,i)>num) {
mark=(int)(Math.pow(2,i)-1-num);
break;
}
if(Math.pow(2,i)==num){
mark=(int)Math.pow(2,i+1)-(int)Math.pow(2,i)-1;
break;
}
}
return mark;
}
}