解法一:
public class Solution {
public int findComplement(int num) {
String s = Integer.toBinaryString(num);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < s.length(); i++){//求出num的二进制的flip形式
char c = s.charAt(i);
if(c == '0'){
sb.append('1');
}else{
sb.append('0');
}
}
//System.out.println(sb);
sb = sb.reverse();//将二进制转换为十进制,从低位开始,所以要反向
//System.out.println(sb);
s = sb.toString();
int res = 0;
int product = 1;//代表二进制每一位的因子
for(int i = 0; i < s.length(); i++){
char c = s.charAt(i);
res += (c - '0') * product;
product *= 2;
}
return res;
}
}