Invert last bit

How can I invert the last bit in 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 do I rewrite invertLastBit()?

+4
source share
2 answers

You can use bitwise XOR:

int x = 5; // 101
x = x ^ 1; // 100

Using the 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
+13
source

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) { //thanks harold
       return i - 1;
   } else {
       return i + 1;
   }
}

It’s easy to see why this works.

+4
source

All Articles