Here is my code:
package com.app;
public class Solution {
// Suppose the operation ~ doesn't exist
public int invertBinaryNumber(int n) {
int singleOne = 1;
int singleZero = 0xfffffffe;
while (singleOne != 0) {
if ((n & singleOne) == 0) {
n |= singleOne;
} else {
n &= (singleZero);
}
singleZero <<= 1;
singleZero |= 1;
singleOne <<= 1;
}
return n;
}
}
And there are a few tests:
package com.app;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class SolutionTest {
@Test
void one() {
Solution solution = new Solution();
assertEquals(~1, solution.invertBinaryNumber(1));
}
@Test
void even() {
Solution solution = new Solution();
assertEquals(~12, solution.invertBinaryNumber(12));
}
@Test
void odd() {
Solution solution = new Solution();
assertEquals(~37, solution.invertBinaryNumber(37));
}
@Test
void intMax() {
Solution solution = new Solution();
assertEquals(~Integer.MAX_VALUE, solution.invertBinaryNumber(Integer.MAX_VALUE));
}
@Test
void intMin() {
Solution solution = new Solution();
assertEquals(~Integer.MIN_VALUE, solution.invertBinaryNumber(Integer.MIN_VALUE));
}
}
The problem seems to be pretty easy. However, it took me some time to make it work with negative numbers and some edge cases. So I'd greatly appreciate if you noticed any bugs in my code.