고양이와 코딩

[LeetCode] Palindrom number 본문

C

[LeetCode] Palindrom number

ovovvvvv 2024. 11. 10. 16:26
728x90

Given an integer x, return true if x is a 

palindrome
, and false otherwise.

 

Example 1:

Input: x = 121
Output: true
Explanation: 121 reads as 121 from left to right and from right to left.

Example 2:

Input: x = -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.

Example 3:

Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

 

Constraints:

  • -231 <= x <= 231 - 1

 

Follow up: Could you solve it without converting the integer to a string?

 

 

solution

bool isPalindrome(int x) {
    if(x == 0){
        return true;
    }

    if (x < 0 || x % 10 == 0){
        return false; 
    }

    char str[12]; // int의 범위는 최대 10자리 + 부호 + null 문자
    sprintf(str, "%d", x);

    int len = strlen(str);
    for(int i = 0; i < len / 2; i++){
        if (str[i] != str[len - i - 1]) {
            return false;
        }
    }
    return true;
}

sprintf를 사용하여 x를 문자열로 변환하여 str배열에 저장한다.

 

'C' 카테고리의 다른 글

[LeetCode] Longest Common Prefix  (3) 2024.11.12
[LeetCode] Roman to Integer  (1) 2024.11.10
[LeetCode] Two Sum  (0) 2024.11.10
함수 포인터 연습문제  (0) 2024.06.16
포인터 진짜 짜증남  (0) 2024.06.15