LeetCode-09-PalindromeNumber

本文最后更新于:a year ago

题目

Determine whether an integer is a palindrome. An integer is a palindrome when it reads the same backward as forward.


Example1
1
2
Input: 121
Output: true

Example1

1
2
3
4
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.

Example3

1
2
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都不是回文数。其他的整数再按照回文的规则判断。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package leetcode;

public class D09_PalindromeNumber {

public static boolean isPalindrome(int x) {
int x1 = x;
int tmp = 0;
if (x1 < 0) return false;
while (x != 0) {
tmp = tmp * 10 + x % 10;
x /= 10;
}
if (tmp == x1) {
return true;
} else {
return false;
}
}

}

复杂度分析

* 时间复杂度:O(log(N)),x中大约有log10(x)位数字。
* 空间复杂度:O(1)


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!