The other day I was linked to a forum discussion on the correct way to reverse the Sign of an integer (e.g., make -5 into 5, or 5 into -5). I was so enthralled by the discussion that I decided to write my own solution:
public static int reverseSign(int x) { /* x is the input number*/ String srcNum = Integer.toString(x); int srcNumIndex = 0;
int startOfNumber = -1; for(int i=srcNum.length()-1;i>=0;i--) { if((srcNum.charAt(i)=='-') && (i < srcNum.length()-1))
{ startOfNumber=i+1; srcNumIndex++; break;} }
if((srcNum.length() == 1) && (srcNum.charAt(0)=='0')) { startOfNumber = 0; }
char newChars[] = new char[srcNum.length() - startOfNumber]; int newCharIndex = 0; if(startOfNumber < 0) { newChars[0]='-'; newCharIndex = newCharIndex+1; }
for(int i = srcNumIndex; i < srcNum.length();i++) { if(newCharIndex < newChars.length) { newChars[newCharIndex] = srcNum.charAt(i); newCharIndex = newCharIndex+1; } }
String finalString = new String(newChars); return Integer.parseInt(finalString); }
public static int reverseSign(int x)
{
return -x;
}
So why did I write that first monstrosity? Before you think I'm crazy Blogspot, hear me out.
int startOfNumber = -1; for(int i=srcNum.length()-1;i>=0;i--) { if((srcNum.charAt(i)=='-') && (i < srcNum.length()-1))
{ startOfNumber=i+1; srcNumIndex++; break;} }
if((srcNum.length() == 1) && (srcNum.charAt(0)=='0')) { startOfNumber = 0; }
char newChars[] = new char[srcNum.length() - startOfNumber]; int newCharIndex = 0; if(startOfNumber < 0) { newChars[0]='-'; newCharIndex = newCharIndex+1; }
for(int i = srcNumIndex; i < srcNum.length();i++) { if(newCharIndex < newChars.length) { newChars[newCharIndex] = srcNum.charAt(i); newCharIndex = newCharIndex+1; } }
String finalString = new String(newChars); return Integer.parseInt(finalString); }
(C++ version available upon request)
An alternative algorithm for this function might look like:
public static int reverseSign(int x)
{
return -x;
}
So why did I write that first monstrosity? Before you think I'm crazy Blogspot, hear me out.
Programmers must be natural economizers. Despite the great strides in CPU speed, memory, and storage capacities, they remain finite resources. Since economics is, among other things, the study of human behavior in the presence of finite goods, it seems fitting that programmers think carefully about how they utilize these resources.