So I am learning Java and doing a bit of basic algorithms (still really new to this).
Say the requirement is to reverse an integer of 5143 so it becomes 3415.
Which of the following is the better way to do it (or is there an even better way)? The two different functions are reverse() and reverseNum (Ability to reverse 0 value is neglected):
public class ReverseIntegers {
public static void main(String[] args) {
reverseNum(5143);
reverse(5143);
}
public static void reverse(int number) {
String numString = Integer.toString(number);
String result = "";
char[] cArray = numString.toCharArray();
for (int i = (cArray.length - 1); i >= 0; i--) {
result += Character.toString(cArray[i]); // concatenate the String numbers in reverse order
}
System.out.println(Integer.parseInt(result));
}
public static void reverseNum(int number) {
int numLength = Integer.toString(number).length();
int[] numArray;
numArray = new int[numLength];
int numMod;
int numModLength;
int result = 0;
for (int i = numLength - 1; i >= 0; i--) {
numMod = (int)(number % Math.pow(10, i + 1)); // eliminate first integer value one by one
numModLength = Integer.toString(numMod).length();
while (numModLength > 1) { // obtain the first integer value of the remainder
numMod = (numMod / 10);
numModLength--;
}
numArray[i] = numMod; // assign the first integer value to the array
}
int digits = numArray.length - 1;
for (int i = 0; i < numArray.length; i++) { // put numbers in the array in reverse sequence
result += numArray[i] * Math.pow(10, digits);
digits--;
}
System.out.println(result);
}
}
The first function is roughly equivalent to:
The second function is (in my opinion) quite hard to read. It is also quite inefficient due to the repeated calls to
Integer.toString().A third alternative (which you haven’t coded up) is to have a function that’s purely based on integer maths and doesn’t use strings at all. It’ll probably be the most efficient of the lot. It will, however, require some care in how it deals with numbers that end in zeroes.
In my view the contest is between the first and the third alternatives; the second function has the shortcomings of both and the advantages of neither.
In the absence of any further information, I’d probably use the code at the start of this answer, and would replace it with something that doesn’t using strings if and only if profiling the app suggests it’s worth doing.