개발/Programming
[ Leetcode ] 9. Palindrome Number - Java
쩨이엠
2021. 3. 8. 20:25
728x90
반응형
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 palindrome while 123 is not.
Example 1:
Input: x = 121 Output: true
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.
Example 4:
Input: x = -101 Output: false
Constraints:
- -231 <= x <= 231 - 1
Solution
class Solution {
public boolean isPalindrome(int x) {
if(x < 0){
return false;
}
int reverse=0;
int temp=x;
while(temp!=0){
reverse = reverse*10 + temp%10;
temp /= 10;
}
return reverse == x;
}
}
풀다보니 int값을 줬을 때 String으로 캐스팅해서 풀면 속도가 엄청 줄어든다 거의 5배정도 차이가 나서
숫자로 풀어보기로 했다
1. 0보다 작은 경우는 -가 붙으므로 무조건 false
2. 숫자를 reverse한다. 나머지를 구하고 다음턴부터 10씩 곱해준다
3. 거꾸로 한 숫자와 같은지 확인한다
728x90
반응형