How to "invert" numbers in Java

I don’t see that you need an algorithm as much. What you have is:

InverseNumber = (myCollection.Length - MySelection);

Thats all you need for even numbers.

With a collection of 1 – 6 for example:
Give 2; 6 – 2 = 4. Also if given 4, 6 – 4 = 2.

You will need a slightly different problem for odds:

1 – 5; with 1 given 1 is at index 0, the opposite is 5, 2 given and the inverse ( 5 – 2) is 3. But if 3 is given, there is no inverse. So you might want to also add a catch for:

if (((myCollection.Length *.5).Round) == mySelection) { //Inverse does not exist!!!}

If you are using just integers, and not arrays of numbers then just replace the myCollection.Length with the upperbound integer.

Leave a Comment