Leet me code 2 - [LeetCode][C++] 9. Palindrome Number (Easy)
leet me code :)
https://leetcode.com/problems/palindrome-number/
Palindrome Number - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
9. Palindrome Number
Given an integer x, return true if x is palindrome integer.
An integer is a palindrome when it reads the same backward as forward.
- For example, 121 is a palindrome while 123 is not.
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
Follow up: Could you solve it without converting the integer to a string?
문제 정리
- Input : 정수 x, -2^31 <= x <= 2^31 - 1
- Output : bool type(Palindrome 여부)
생각의 흐름
그냥 한자리씩 잘라서 배열에 넣고 비교할까..?
근데 문제 분류가 Math라 그냥 수학으로..
절대로 palindrome이 될 수 없는 숫자는 음수, 마지막 자리가 0으로 끝나는 수(0은 제외)
x의 마지막 자리 수를 떼어내서 새로운 수 y를 만든다.
x가 더 작아질 때까지 반복하고, x와 y 비교
1 | 2 | 3 | 2 | 1 | > | |||
1 | 2 | 3 | 2 | > | 1 | |||
1 | 2 | 3 | > | 1 | 2 | |||
1 | 2 | < | 1 | 2 | 3 |
1 | 2 | 2 | 1 | > | ||
1 | 2 | 2 | > | 1 | ||
1 | 2 | == | 1 | 2 |
Solution 코드
class Solution {
public:
bool isPalindrome(int x) {
if ((x < 0) || (x % 10 == 0 && x != 0)) {
return false;
}
int y = 0;
while (x > y) {
y = y * 10 + x % 10;
x = x / 10;
}
if (x == y || x == y / 10) {
return true;
}
return false;
}
};