거꾸로 읽어도 동일한 수를 palindrome이라고 한다. 주어진 수가 palindrome인지 확인하라.
Input: x = 121
Output: true
Input: x = -121
Output: false
1. Constraints
- x integer can be negative number
- -2^31 <= x <= 2^31 - 1
- the backward -121 is 121-
- 1221 <- palindrome
2. Ideas
- make string through sprintf(), and strcmp(orig, back) -> O(N)?
- how to check two strings. -> linear
3. Test Cases
- single number, negative single number
- maximum integer
- negative number
- check access out of array of strx[]
4. Coding
#include <string.h>
bool isPalindrome(int x){
if (x < 0)
return false;
char *strx = (char *)calloc(12, sizeof(char));
sprintf(strx, "%d", x);
int ssize = strlen(strx);
for (int i = 0; i < (ssize / 2); i++)
if (strx[i] != strx[ssize - 1 - i])
return false;
return true;
}