[Leetcode] 9. Palindrome Number

2024. 3. 12. 23:14Tech: Algorithm


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:

  • -2^31 <= x <= 2^31 - 1

Solution

숫자가 주어졌을때 palindrom인지 아는 방법인데 이건 문자열로 바꿔서 index 끝과 처음을 비교하는 방법으로 해도될 것 같음..! to_string 함수를 이용해서 아래와 같이 빠르게 Clear!

class Solution {
public:
    bool isPalindrome(int x) {
        string s = to_string(x);
        int l = s.length();
        for(int i=0;i<l/2;i++)
        {
            if(s[i]!=s[l-i-1]) return false;
        }
        return true;
    }
};

그런데..!! 답을 푼 사람들 것을 보니 string이 아닌 숫자만을 썼어야한다는 점을 깨달았다..ㅎㅎ

아래와 같이 reversed라는 변수에 반절을 저장하고 마지막에 reversed 변수와 x가 같은지 보면 되는 부분..! 이때 reversed/10일때도 보는 이유는 자릿수가 만약 혹수자리수일때 (ex. 121, 191) 가운데 자리는 무시하면 되기 때문

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0 || (x != 0 && x % 10 == 0)) {
            return false;
        }

        int reversed = 0;
        while (x > reversed) {
            reversed = reversed * 10 + x % 10;
            x /= 10;
        }
        return (x == reversed) || (x == reversed / 10);
    }
};