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: 5Output: 2Explanation: 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: 1Output: 0Explanation: The binary representation of 1 is 1 (no leading zero bits), and its complement is 0. So you need to output 0.
题意:给一个正整数,返回其补数。所谓补数就是。。。。1的补数是0.把每一位求补返回就好。
public class Solution {
public int findComplement(int num) {
int cp=num;
int ans=0;
while(cp!=0){
cp=cp/2;
ans++;
}
return num^(int)(Math.pow(2,ans)-1);
}
}
PS:利用了异或的性质
A^1=-A。
先用ans求出正整数的二进制位数,然后直接与项ans个1表示的二进制和其异或即可。
转载于:https://blog.51cto.com/fulin0532/1890949