This is part of a longer coding challenge - one part involves "flipping" the digits of an input number (i.e. 1234 becomes 4321) and removing leading zeros as applicable.
Below, I have written the method flipOpp that accomplishes this. Most of the time, it works perfectly. But sometimes, I'm getting an error because the last digit becomes a dash ("-") and obviously, the Integer.parseInt() method won't work if one of the digits is a dash!
Any ideas what might be causing this? Also, is there an easier way to flip the digits of an int? The method I'm using right now doesn't seem very efficient - turning an int to a String, then to a character array, manipulating the characters of this array, turning it back into a String, and finally back to an int.
Thanks! Code for this method is below:
// third operation: reverse the digits and remove leading zeros
public static int flipOpp(int num){
char temp;
// change int to a String
String stringNum = Integer.toString(num);
// change String to a char array of digits
char[] charNum = stringNum.toCharArray();
// flip each character and store using a char temp variable
for (int i=0;i<charNum.length/2;i++){
temp = charNum[i];
charNum[i]=charNum[charNum.length-i-1];
charNum[charNum.length-i-1]=temp;
}
// turn flipped char array back to String, then to an int
// this process removes leading zeros by default
String flipString = new String(charNum);
if (flipString.length()<7){
int flipInt = Integer.parseInt(flipString);
return flipInt;
}
else return 0;
}