问题:
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.
解决:
① 注意对输入的数值转换时是32位二进制数,高位为0,不算在计算范围内,应该跳过,从第一个非0数据开始。
class Solution { // 10ms
public int findComplement(int num) {
int tmp = (Integer.highestOneBit(num) << 1) - 1; //00..11..1
num = ~ num;//111...取反之后的值
return num & tmp;//000...补码
}
}
进化版:异或的性质---与0相^保留原值,与1相^按位取反,与自身相^结果为0.
public class Solution { // 11ms
public int findComplement(int num) {
int mask = (Integer.highestOneBit(num) << 1) - 1;
return num ^ mask;
}
}
② 利用异或的性质。
class Solution { // 11ms
public int findComplement(int num) {
int tmp = num;
int count = 0;//记录非0的位数
while(tmp != 0){
tmp /= 2;
count ++;
}
return num ^ (int)(Math.pow(2,count) - 1);
}
}
来源:oschina
链接:https://my.oschina.net/u/2968041/blog/1518541