classSolution {publicint findComplement(int num) {
int quotient = num;
int remainder;
int ans = 0;
intcount = 0;
while (quotient != 0) {
remainder = quotient % 2;
ans += (remainder ^ 1) * Math.pow(2, count);
count++;
quotient /= 2;
}
return ans;
}
}
改进1
用位运算取二进制的表示,<<相当于×2(有符号),>>>相当于/2(无符号)
class Solution {
publicintfindComplement(int num) {
int remainder;
int ans = 0;
int bit = 1;
while (num != 0) {
remainder = num & 1;
ans += (remainder ^ 1) * bit;
bit = bit << 1;
num = num >>> 1;
}
return ans;
}
}