java - Invert last bit -



java - Invert last bit -

how can invert lastly bit in int?

int = 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"; } homecoming integer.parseint(s, 2); }

but how should rewrite invertlastbit() ?

you can utilize bitwise xor :

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

using original illustration :

int = 11; system.out.println (a + " " + integer.tobinarystring(a)); //11 1011 int b = a^1; system.out.println (b + " " + integer.tobinarystring(b)); //10 1010

java int bit invert

Comments

Popular posts from this blog

formatting - SAS SQL Datepart function returning odd values -

c++ - Apple Mach-O Linker Error(Duplicate Symbols For Architecture armv7) -

php - Yii 2: Unable to find a class into the extension 'yii2-admin' -