Leetcode / 1009. Complement of Base 10 Integer
Pick a programming language:
Here is the source code for the solution to this problem.
class Solution {
public int bitwiseComplement(int n) {
if (n == 0) {
return 1;
}
int i = 30;
while (i >= 0) {
int bit = n & (1 << i);
if (bit > 0) {
break;
}
i--;
}
int mask = (1 << i + 1) - 1;
return ~n & mask;
}
}
Did you like the lesson? 😆👍
Consider a donation to support our work: