-4

I am converting the given int to binary represention which is string, and then traversing the string and changing each char/bit in string and then converting back to required int.

Myquestion is, is there a mathematical or better way to do this?

codeZach
  • 39
  • 5

2 Answers2

0

Using the bitwise operator ~ (not) you can do it without iteration. Example method:

public static int flipBits(int n) {
    return ~n;
}

You can also do it without a method, but for a general use using a method may be easier.

Zoe
  • 27,060
  • 21
  • 118
  • 148
0

Okay I got one more solution in which we find the maximum number that can be formed by digit's length bit, i.e for 5 `101' we can get 111 which is 7, so we subtract 7-5(given number) = 2, required solution

codeZach
  • 39
  • 5