# 引言
题目链接:https://leetcode.com/problems/palindrome-number/description/
# 题目大意
判断一个数字是不是回文数字。
- Example
Input: 121
Output: true
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
# 题解
# 一句话题解
一个数字为回文数字,则对称点后半部分的翻转数字和前半部分的数值相等,模拟判断即可 (特判:负数和末尾为零的非零数字直接返回 false
)
复杂度 O(n)
# AC 代码
c++
版本
class Solution | |
{ | |
public: | |
bool isPalindrome(int x) | |
{ | |
if (0 == x) | |
{ | |
return true; | |
} | |
if (x < 0 || 0 == x % 10) | |
{ | |
return false; | |
} | |
int reverseNum = 0; | |
while (reverseNum < x) | |
{ | |
reverseNum = reverseNum * 10 + x % 10; | |
x /= 10; | |
} | |
return reverseNum == x || reverseNum / 10 == x; | |
} | |
}; |
go
版本
func isPalindrome(x int) bool { | |
if 0 == x { | |
return true | |
} | |
if x < 0 || 0 == x%10 { | |
return false | |
} | |
reverseNum := 0 | |
for reverseNum < x { | |
reverseNum = reverseNum*10 + x%10 | |
x = x / 10 | |
} | |
return reverseNum == x || reverseNum/10 == x | |
} |