How can I invert the last bit in an int
?
int a = 11;
System.out.print(a + " " + Integer.toBinaryString(a)) //11 1011
int b = invertLastBit(a);
System.out.print(b + " " + Integer.toBinaryString(b)); //10 1010
I wrote this:
static int invertLastBit(int i)
{
String s = Integer.toBinaryString(i);
if (s.charAt(s.length()-1) == '0'){
s = s.substring(0,s.length() - 1);
s = s+"1";
}else if (s.charAt(s.length()-1) == '1') {
s = s.substring(0, s.length() - 1);
s = s + "0";
}
return Integer.parseInt(s, 2);
}
But how should I rewrite invertLastBit()
?
To flip one or more bits, use binary XOR. In your case, the appropriate XOR mask is 1 shifted k bits to the left. is valid in C, Java, Python and a few other languages (provided the variables are appropriately defined).
In digital logic, an inverter or NOT gate is a logic gate which implements logical negation.
In binary, when we subtract a number A from a number of all 1 bits, what we're doing is inverting the bits of A. So the subtract operation is the equivalent of inverting the bits of the number.
C++ bitset flip() function is used to flip all the bit values converting zeros to ones and ones to zeros. If a parameter 'position' is passed, it flips the bit at the specified position only.
You can use bitwise XOR :
int x = 5; // 101
x = x ^ 1; // 100
Using your original example :
int a = 11;
System.out.println (a + " " + Integer.toBinaryString(a)); //11 1011
int b = a^1;
System.out.println (b + " " + Integer.toBinaryString(b)); //10 1010
You don't even have to worry about converting to binary.
If the number if odd, the last bit has to be one, thus, subtract 1 from the number.
Otherwise, if the number is even, the last bit has to be 0, add 1 to the number.
That's all.
static int invertLastBit(int i){
if(i % 2 != 0) { //thanks harold
return i - 1;
} else {
return i + 1;
}
}
It is not difficult to reason about why this works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With