[Leetcode] 9. Palindrome Number
[Leetcode] 9. Palindrome Number

[Leetcode] 9. Palindrome Number

카테고리
📚 Algorithm
작성자
박용성박용성
작성일
2024년 09월 02일
태그
Python
Leetcode
C++
Slug
Leetcode-9
floatFirstTOC: right

🖥️ 시작하며

쉬운 문제다.
Example 2:
문제 조건에 이와 같이 부호도 한꺼번에 회문으로 처리하니 우선 음수는 조건에 부합하지 않은 것으로 처리한다. 그 후 숫자를 뒤집어주면 된다.
 

⚙️ Python

class Solution: def isPalindrome(self, x: int) -> bool: if x < 0: return False else: x = str(x) return x == x[::-1] if __name__ == "__main__": sol = Solution() print(sol.isPalindrome(10)) # True
 

⚙️ C++

#include <cctype> #include <iostream> #include <limits> #include <string> class Solution { public: bool isPalindrome(int x) { if (x < 0) { return false; } int reversed = 0; int original = x; while (x != 0) { int digit = x % 10; x /= 10; if (reversed > (std::numeric_limits<int>::max() - digit) / 10) { return false; } reversed = reversed * 10 + digit; } return original == reversed; } }; int main() { Solution sol; std::cout << sol.isPalindrome(-42) << std::endl; // -42 return 0; }
 

📌 소감

 

댓글

guest