Description
주어진 int값이 거꾸로 시작해도 일치하는 값일 경우 true, 아니면 false를 반환합니다.
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?
Solution 1. String 변환
public boolean isPalindrome(int x) {
// return negative int
if(x < 0){
return false;
}
// convert int to String
String intStr = Integer.valueOf(x).toString();
int len = intStr.length();
for(int i=0; i< len/2; i++){
if(intStr.charAt(i) != intStr.charAt(intStr.length()-1-i)){
return false;
}
}
return true;
}
주어진 int값을 String으로 변환한뒤 앞뒤 값을 비교해 나갑니다.
Reference
'알고리즘 > LeetCode' 카테고리의 다른 글
[LeetCode] 438. Find All Anagrams in a String - 문제풀이 (0) | 2022.02.03 |
---|---|
[LeetCode] 77. Combinations - 문제풀이 (0) | 2022.02.02 |
[LeetCode] 145. Binary Tree Postorder Traversal - 문제풀이 (0) | 2022.01.29 |
[LeetCode] 94. Binary Tree Inorder Traversal - 문제풀이 (0) | 2022.01.28 |
[LeetCode] 144. Binary Tree Preorder Traversal - 문제풀이 (0) | 2022.01.27 |