Home About Me

All I Wanted Was to Flip a Sign

A thread on Sun’s Java forums began with a beginner’s plea: how do you reverse the sign of an integer in Java? The poster wanted to turn -12 into +12, said they had spent a whole day on it, and asked for a method, a math library, a binary trick—anything pointing in the right direction.

The first reply was:

n = -n;

The original poster came back a few posts later: they knew it had to be simple, but not that simple. They thanked the respondent. Then, after trying it: “No joke—I tried it, and it really works.”

It is the kind of thread that would be familiar on Chinese forums too: a naive question that invites more mockery than help. Internet culture is not so different abroad. There are plenty of pranksters. But one thing is worth noting: even when the replies were absurd, they stayed on the problem and avoided personal insults.

The second reply opened the floodgates:

int x = numberToInvertSign;
boolean pos = x > 0;
for(int i = 0; i < 2*Math.abs(x); i++){
    if(pos){
        numberToInvertSign--;
    }
    else{
        numberToInvertSign++;
    }
}

Someone pointed out that n = -n works but is not obscure enough. So came:

int n = ....;
 n = (0xffffffff ^ n) + 1;

Then more deceptively simple but obscure options:

n = ~n + 1;

n = ~--n;

And then:

n^= 0xffffffff;
int m;
for (m= 1; m != 0 && ((n&m) != 0); m<<= 1);
n|= m;
if (m == 0) n= m;
else for (m >>= 1; m != 0; n^= m, m>>=1);

The for loops in that one drew their own discussion. It was around this point that the thread stopped pretending to be practical.

public int invert(int i) {
  return i - (i + i);
}
switch (i)
{
  case 1: return -1;
  case 2: return -2;
  case 3: return -3;
  // ... etc, you get the proper pattern
}

Then came this:

int absoluteValue(int num)
{
 int max = 0;
 for(int i = 0; true; ++i)
 {
  max = i > max ? i : max;
  if(i == num)
  {
   if(i >= max)
    return i;
   return -i;
  }
 }
}

A string-based solution followed:

public int invert(int n) {
    String nStr = String.valueOf(n);

    if (nStr.startsWith("-")) {
        nStr = nStr.replace("-", "");
    } else {
        nStr = "-" + nStr;
    }

    return Integer.parseInt(nStr);
}

And since this is Java, someone eventually remembered object orientation:

public interface Negatable<T extends Number> {
  T value();
  T negate();
}



public abstract class NegatableInteger implements Negatable<Integer> {
  private final int value;

  protected NegatableInteger(int value) {
    this.value = value;
  }

  public static NegatableInteger createNegatableInteger(int value) {
    if (value > 0) {
      return new NegatablePositiveInteger(value);
    }
    else if (value == Integer.MIN_VALUE) {
      throw new IllegalArgumentException("cannot negate " + value);
    }
    else if (value < 0) {
      return new NegatableNegativeInteger(value);
    }
    else {
      return new NegatableZeroInteger(value);
    }
  }

  public Integer value() {
    return value;
  }

  public Integer negate() {
    String negatedString = negateValueAsString ();
    Integer negatedInteger = Integer.parseInt(negatedString);
    return negatedInteger;
  }

  protected abstract String negateValueAsString ();
}



public class NegatablePositiveInteger extends NegatableInteger {
  public NegatablePositiveInteger(int value) {
    super(value);
  }

  protected String negateValueAsString () {
    String valueAsString = String.valueOf (value());
    return "-" + valueAsString;
  }
}



public class NegatableNegativeInteger extends NegatableInteger {
  public NegatableNegativeInteger (int value) {
    super(value);
  }

  protected String negateValueAsString () {
    String valueAsString = String.valueOf (value());
    return valueAsString.substring(1);
  }
}



public class NegatableZeroInteger extends NegatableInteger {
  public NegatableZeroInteger (int value) {
    super(value);
  }

  protected String negateValueAsString () {
    return String.valueOf (value());
  }
}

At first the thread looked like a two-page curiosity, not a major event. Then it was cross-posted to Reddit, and the replies passed 490. Suggestions there included wrapping the operation in try/catch and moving the sign-flipping logic into an XML configuration file. Programmers kept chasing more twisted and extravagant solutions, clearly enjoying themselves.

The verdict was hard to escape: programming is hard.

Nor was this an isolated case. On PHP’s official site, the documentation comments for the abs function turned into a similar long thread, complete with performance analysis. It was, in its own way, impressive.