[LeetCode 9] Palindrome Number
LeetCode 9 (Java)
[Palindrome Number] 문제 풀이
[LeetCode 9] Palindrome Number
Description
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.
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
Hint
Hint 1
Beware of overflow when you reverse the integer.
Code
내 제출
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) { // 음수인 경우 false return
return false;
} else if (x == 0) {
return true;
} else if ((x % 10) == x) {
return true;
}
// 문자열로 변환 후 대조
String str = "" + x;
char[] strs = str.toCharArray();
int result = 0;
int len = (int)Math.ceil((double)strs.length / 2); // result 값과 비교하여 true 반환
for (int i = 0; i < len; i++) {
for (int j = ((strs.length - 1) - i); j > 0; j--) {
if (strs[i] == strs[j]) {
result++;
break;
} else {
return false;
}
}
}
if (result == len) {
return true;
}
return false;
}
}
| Runtime | Memory |
|---|---|
| 7 ms | 44.2 MB |
다른 풀이
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean isPalindrome(int x) {
if (x < 0) {
return false;
}
int q = 0, o = x;
while (x > 0) {
q = (x % 10) + q * 10;
x = x / 10;
}
return q == o;
}
}
Reference
This post is licensed under CC BY 4.0 by the author.
