leetcode - 9. Palindrome Number

숲사람·2022년 5월 26일
0

멘타트 훈련

목록 보기
34/237

문제

거꾸로 읽어도 동일한 수를 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;
}
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글