public class Symmetric {
// Solution A
int[] digits = new int[] {};
boolean symmetrical(int i) {
int n = i;
int index = 0;
while (n != 0) {
digits[index++] = n % 10;
n = n / 10;
}
return symmetrical(digits, 0, digits.length - 1);
}
//recursive way to just if the array is symmetrical
boolean symmetrical(int[] digits, int begin, int end) {
if (begin >= end)
return true;
return (digits[begin] == digits[end])
&& symmetrical(digits, begin + 1, end - 1);
}
//traditional way to judge if the array is symmetrical
boolean symmetrical(int[] digits, int begin,int end){
int length = (end - begin)/2;
for(int i=0;i< length;i++){
if(digits[begin+i] != digits[end-i]){ return false;}
}
return true;
}
//end of Solution A
// Solution B
//just compute the new number from the end to first. This method is recommended since there is no need to assign an new int[] array.
boolean symmetrical_B(int i) {
int n = i;
int m = 0;
int t = 0;
while (n != 0) {
t = n % 10;
m = m * 10 + t;
n = n / 10;
}
return m == i;
}
}
When using the first algorithm, the algorithm tries to convert an integer into an array. That’s really a space consuming method. For every single problem, please consider just using the existing space and data structure, don’t try to convert the existing data structure into another structure.