넘치게 채우기

[LeetCode] 9. Palindrome Number 본문

PS/LeetCode

[LeetCode] 9. Palindrome Number

riveroverflow 2023. 10. 24. 18:13
728x90
반응형

 

https://leetcode.com/problems/palindrome-number/description/

 

Palindrome Number - LeetCode

Can you solve this real interview question? Palindrome Number - 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. Ex

leetcode.com

leetcode - Palindrome Number

문제 유형 : 수학 / 구현 / 문자열처리

문제 난이도 : Easy

 

문제

Given an integer x, return true if x is a palindrome and false otherwise.

 

정수 x가 주어집니다. 팰린드롬이면(뒤집어도 같은 숫자이면) true를 아니면 false를 반환하시오.

 

풀이

음수라면 false를 무조건 반환시키고,

 

0 이상인 경우에는 문자열로 만들어서 뒤집은 문자열과 비교해서 같으면 팰린드롬 넘버입니다.

 

코드

C++

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        
        string str = to_string(x);
        string reversedStr = str;
        reverse(reversedStr.begin(), reversedStr.end());

        return str == reversedStr;
    }
};
 
728x90
반응형