leetcode-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 palindrome while 123 is not.

Example 1:

1
2
Input: x = 121
Output: true

Example 2:

1
2
3
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:

1
2
3
Input: x = 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.

Example 4:

1
2
Input: x = -101
Output: false

Constraints:

  • -231 <= x <= 231 - 1

Follow up: Could you solve it without converting the integer to a string?

分析


简单题。

解决方案1(Python)


1
2
3
class Solution:
def isPalindrome(self, x: int) -> bool:
return str(x)== str(x)[::-1]

解决方案2(C++)


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
class Solution {
public:
bool isPalindrome(int x) {
if(x < 0) {
return false;
}
if(x == 0) {
return true;
}
int base = 1;
while(x / base >= 10) {
base *= 10;
}

while(x) {
int left = x / base;
int right = x % 10;
if(left != right){
return false;
}
x -= base*left;
base /= 100;
x /= 10;
}
return true;
}
};

解决方案3(Golang)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func isPalindrome(x int) bool {
if x < 0 {
return false
}
nums := []int {}
for x != 0 {
nums = append(nums, x%10)
x /= 10
}
length := len(nums)
for i := 0; i < length/2; i++ {
if nums[i] != nums[length-i-1] {
return false
}
}
return true
}

相关问题


题目来源