In java, using a zero as the most significant digit, it interpreters the number as an octal number. So 01234
gets converted to:
4 + 3 x 8 + 2 x 8^(2) + 1 x 8^(3) = 668
So you are better off with using one of the convert-to-string methods as in the other answers.
Edit: Here is a version without StringBuffer etc.:
public String getReversed(int number) {
char[] digitArray = String.valueOf(number).toCharArray();
String strNum = "";
for (int i = digitArray.length - 1; i >= 0; i--) {
strNum += digitArray[i];
}
return strNum;
}
2nd edit: Reversing a char
array and then create the String
after finished reversing, because of a possible creation of number of O(n^2)
operations that could be a problem for the garbage collector.
public String getReversed(int number) {
char[] digitArray = String.valueOf(number).toCharArray();
char[] reversedDigitArray = new char[digitArray.length];
for (int i = 0; i < digitArray.length; i++) {
reversedDigitArray[i] = digitArray[digitArray.length - i - 1];
}
return new String(reversedDigitArray);
}
3rd Edit: Swaps chars with in-place algorithm.
public static String getReversed(int number) {
char[] digitArray = String.valueOf(number).toCharArray();
int count = digitArray.length - 1;
char tmp;
for (int i = (count-1) >> 1; i >= 0; --i) {
tmp = digitArray[i];
digitArray[i] = digitArray[count - i];
digitArray[count - i] = tmp;
}
return new String(digitArray);
}