It never ceases to amaze me the lengths that certain programmers will go to solve the simplest of problems. Like, say, negation.

When "n * (-1)" Won't do ...

Originally published on August 12, 2004.

... just come up with an overly complicated function that achieves the same thing, like this one discovered by "mightydog":

There's More Than One Way To Neg. A Num.

Originally published on November 15, 2005.

Programmers have an innate desire to reinvent, over-engineer, and over-complicate things. I've always believed it's a result of the "fun" gap between what's needed (a simple HTML form with a generic FormMail.asp script) and what's challenging (a 12-layer Service Oriented Architecture involving a XML-configurable wrappers for every framework class, HtmlFormConfigurationHandlerProviders, FormEmailManagers, a FormEmailManagerFactory, a FormEmailManagerFactoryFactory, and so on).

The good programmer will fight his urge to build The Greatest System Ever Built, instead providing a more modest solution. Dwayne's colleague, on the other hand, will make sure that nothing is as simple as multiplying by -1 ... Dwayne

 

//function performs the negation for integer.
public int getNegate(int n)
{
  string strBin = ConvertToBin(n);
  string strNegation = "";
  int c,count,i;
  int nDec;

  if (strBin.Length != 8)
    for(i=strBin.Length; i<8; i++)
      strBin = "0" + strBin;

  count = 1;
  while (count <= strBin.Length)
  {
    c = Convert.ToInt32(strBin.Substring(count-1,1));
    if (c == 1)
      strNegation = strNegation + "0";
    else
      strNegation = strNegation + "1";
    count = count + 1;
  }
  nDec = ConvertDecimal(strNegation);
  return nDec;
}