o9s
is a microblog
home archives search feed blogroll


flipSign

Yesterday I came across a joke project that uses a giant switch statement to flip the sign of a number.

It goes something like this.

function signFlip(num) {
    switch (num) {
        case 0:
            return -0;
        case -0:
            return 0;
        case 1:
            return -1;
        case -1:
            return 1;
        // ...
        case 9:
            return -9;        
        case -9:
            return 9;
        // ...
        case 9007199254740991:
            return -9007199254740991;
        case -9007199254740991:
            return 9007199254740991;
        default:
            return num-num*2;
    }
}

It even provides a fully working REST API. Try it for yourself.

https://gg-flip.herokuapp.com/api/v1/flip?num=69

It gave me inspiration to also implement a dumb way to flip the sign of a number. The previous code is in JavaScript, my code is in Java.

public int flipSign(int x) {
  String xAsString = x + "";

  if (xAsString.startsWith("-")) {
    xAsString = xAsString.substring(1);
  } else {
    xAsString = "-" + xAsString;
  }

  return Integer.parseInt(xAsString);
}

By the way, you should just use a minus sign to flip the sign.

Posted on 2018-01-24   #java     #javascript  






← Next post    ยท    Previous post →