Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invert last bit

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() ?

like image 227
maks28rus Avatar asked Nov 05 '14 05:11

maks28rus


People also ask

How do you flip a certain bit?

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).

Which gate is used to invert the bits?

In digital logic, an inverter or NOT gate is a logic gate which implements logical negation.

How do you invert a binary number?

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.

How do I reverse a bit in CPP?

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.


2 Answers

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
like image 92
Eran Avatar answered Oct 26 '22 18:10

Eran


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.

like image 23
axiom Avatar answered Oct 26 '22 18:10

axiom