问题描述:
Given a positive integer num, output its complement number. The complement strategy is to flip the bits of its binary representation.
将一个数字(的二进制表示)翻转,返回新的数
限制:32位,且没有leading 0(比如,5就是101, 不是00000000101)
方案一:通过字符串解决数字转换问题,比较直观,但不高效
思路:将原数字(十进制)转化为二进制字符串,再将其每一位翻转,输出翻转后二进制字符串所代表的(十进制)整数
该方法需要用到java的几个功能: Integer.toBinaryString(num), Integer.parseInt(str, radix)。前者将十进制int转化为二进制字符串,后者将字符串转化成对应的十进制int(比如将二进制字符串转化为十进制int,radix=2),且忽略字符串打头的0
代码如下:
class Solution {
public int findComplement(int num) {
//to binary string
String s=Integer.toBinaryString(num);
//compute the length of binary string
int length=s.length();
//go through s and flip the bit
String ans="";
for (int i=0; i<length; i++){
if(s.charAt(i)=='0'){
ans=ans+"1";
}
else{
ans=ans+"0";
}
}
//return the decimal value that ans represents
return Integer.parseInt(ans, 2);
}
}
方案二:用位移操作符解,这也是这道题目的设计初衷
思路:翻转一个bit我们可以用XOR(^)操作符,它表示异或关系,0 ^ 1 = 1, 1 ^ 1 = 0 。所以我们可以设计一个蒙版,这个蒙版是动态的,从1开始,接着变成10,100,1000,10000 … 随着1位置的左移,这个动态的1会配合 ^ 操作符对原数字每一位进行翻转,直到到达原数字的尽头
class Solution {
public int findComplement(int num) {
//create a mask which starts from 1
int mask=1;
int ans=num;
while(num>0){ //loop until num drop to 0
ans=ans^mask;
mask=mask<<1;
num=num>>1;
}
return ans;
}
}
时间复杂度: O(1)因为我们最多循环32次