This is from a hacker rank practice problem(not a competition) https://www.hackerrank.com/challenges/flipping-bits. Just doing this for practice.
The problem just asks you to take a set number for 32 bit integers and for each one, invert all the bits inside that integer and print out the result
Here's my code so far
static long getComplement(long c) {
long complement = 0;
for(int k = 31; k >= 0 ; k --) {
long evaluateBit = c >> k;
if(evaluateBit == 1) {
evaluateBit = 0;
} else {
evaluateBit = 1;
}
complement += evaluateBit << k;
}
return complement;
}
Here is my high level pseudo code thinking. I will evaluate every bit in the integer. To do this, I have to right shift the bit by its position(something that was at position 31 would have to be right shifted by 31 to get to position 0 so I can evaluate it). That's why my loop started at 31 and ends at 0. And then once i get the bit at that position, I will invert it with a conditional statement and then left shift the result by the same result. I will finally add it to the sum I am keeping (what was 0 * 2 ^ 31 will consist of 1 * 2 ^ 31)
Does anyone see any problems with my pseudo code?
There has to be a problem because when I tried running the code in my IDE, here is what I got when I debugged the code
I tried doing a test run with a input of 0. After my first run(k=31), I somehow get a negative number. Does anyone know what the problem is or how I can fix this?
I made sure that I used the right shift operators as well, from How do shift operators work in Java?