https://leetcode.com/problems/number-complement/
The following are two valid solutions for this problem, why did I run into an integer overflow in the first solution when I had the mask
variable to be an int (instead of a long), and why was I able to get away with an int variable type for the mask
in the second solution
public int findComplement(int num) {
// Make a copy of the number for length estimation purposes , because we will begin mutating it
// directly
int input = num;
// Use a power of two mask to bring 1 at every position and flip in stages using XOR
for (long mask = 1; mask <= input; mask *= 2) {
num = (int) (num ^ mask);
}
return num;
}
public int findComplement2(int num) {
int save = num;
int mask = 1;
while (save != 0) {
num = num ^ mask;
mask = mask << 1;
save = save >> 1;
}
return num;
}