You don’t even have to worry about converting to binary.
If the number, if odd, the last bit must be one, so subtract 1 from the number.
Otherwise, if the number is even, the last bit should be 0, add 1 to the number.
What all.
static int invertLastBit(int i){
if(i % 2 != 0) {
return i - 1;
} else {
return i + 1;
}
}
It’s easy to see why this works.
source
share