Palindrome Number(验证回文数字) – 每天一道算法题
题目 #
Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
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.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
题目大意 #
判断一个整数是否是回文数。回文数是指正序(从左向右)和倒序(从右向左)读都是一样的整数。
解题思路 #
- 判断一个整数是不是回文数。
- 简单题。注意会有负数的情况,负数,个位数,10 都不是回文数。其他的整数再按照回文的规则判断。
golang代码 #
package leetcode
import "strconv"
// 解法一
func isPalindrome(x int) bool {
if x < 0 {
return false
}
if x == 0 {
return true
}
if x%10 == 0 {
return false
}
arr := make([]int, 0, 32)
for x > 0 {
arr = append(arr, x%10)
x = x / 10
}
sz := len(arr)
for i, j := 0, sz-1; i <= j; i, j = i+1, j-1 {
if arr[i] != arr[j] {
return false
}
}
return true
}
// 解法二 数字转字符串
func isPalindrome1(x int) bool {
if x < 0 {
return false
}
if x < 10 {
return true
}
s := strconv.Itoa(x)
length := len(s)
for i := 0; i <= length/2; i++ {
if s[i] != s[length-1-i] {
return false
}
}
return true
}
java代码 #
class Solution {
public boolean isPalindrome(int x) {
// 特殊情况:
// 如上所述,当 x < 0 时,x 不是回文数。
// 同样地,如果数字的最后一位是 0,为了使该数字为回文,
// 则其第一位数字也应该是 0
// 只有 0 满足这一属性
if (x < 0 || (x % 10 == 0 && x != 0)) {
return false;
}
int revertedNumber = 0;
while (x > revertedNumber) {
revertedNumber = revertedNumber * 10 + x % 10;
x /= 10;
}
// 当数字长度为奇数时,我们可以通过 revertedNumber/10 去除处于中位的数字。
// 例如,当输入为 12321 时,在 while 循环的末尾我们可以得到 x = 12,revertedNumber = 123,
// 由于处于中位的数字不影响回文(它总是与自己相等),所以我们可以简单地将其去除。
return x == revertedNumber || x == revertedNumber / 10;
}
}
声明:本站(www.mysqlschool.cn)所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。