public static int countBits(int i) { int bits = 0; int temp = i; while (temp > 0) { temp = temp / 2; bits++; } return bits; } public static int invertBits(int i) { return i ^ ((int)Math.pow(2, countBits(i)) - 1); }