-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPalindromeNumber.java
More file actions
33 lines (26 loc) · 896 Bytes
/
PalindromeNumber.java
File metadata and controls
33 lines (26 loc) · 896 Bytes
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
package math;
/**
* Description: https://leetcode.com/problems/palindrome-number
* Difficulty: Easy
* Time complexity: O(n)
* Space complexity: O(1)
*/
public class PalindromeNumber {
public boolean isPalindrome(int x) {
if (x < 0) return false; // negative number can't be a palindrome
int tmp = x;
int reversedX = 0;
while (tmp != 0) {
int digit = tmp % 10;
// not really necessary, but it seems easier to add this check,
// than to prove that in case of overflow we will still return false
if (reversedX > Integer.MAX_VALUE / 10
|| (reversedX == Integer.MAX_VALUE / 10 && digit > Integer.MAX_VALUE % 10)) {
return false;
}
reversedX = reversedX * 10 + digit;
tmp = tmp / 10;
}
return x == reversedX;
}
}