I'm writing some useful functions in C. One of them is isPalindrome()
.
I figured to determine if a number is a palindrome or not, I should...
- get all digits in an array
- iterate through with two indexes - start one at 0 and one to the array count
- increment/decrement the indexes whilst subscripting the array whilst they match and if the array count gets to 0 we have a palindrome (i.e. finishing going through all digits).
I came up with...
int isPalindrome(int num) {
int places[100];
int i = 0;
while (num > 0) {
places[i++] = num % 10;
num /= 10;
}
int j = 0;
while (i >= 0 && places[j++] == places[--i]) {
}
return i == -1;
}
Is this generally how it is done?
I'm learning C by myself, and although I can tell when my code compiles and doesn't take all day to work something out, I don't have any expert eyes to tell me if I'm on the right track.
So, any improvements or suggestions on my code?
Thanks very much!