In this method, we convert the integer to a string and check if it reads the same forwards and backwards. This approach is straightforward and leverages the built-in string operations.
Time Complexity: O(n), where n is the length of the string representation of the number.
Space Complexity: O(n) for the string conversion.
1public class Solution {
2 public boolean isPalindrome(int x) {
3 if (x < 0) return false;
4 String str = Integer.toString(x);
5 int n = str.length();
6 for (int i = 0; i < n / 2; i++) {
7 if (str.charAt(i) != str.charAt(n - i - 1)) return false;
8 }
9 return true;
10 }
11}
12
The method first checks if the number is negative. If so, it returns false because no negative number can be a palindrome. It then converts the integer to a string and checks corresponding characters from the start and end of the string to determine if they match.
This approach avoids the use of string conversions by reversing half of the digits of the number and comparing the two halves. This is more memory efficient as it only creates a few integer variables.
Time Complexity: O(log10(n)), where n is the input number because we are dividing the number by 10 in each iteration.
Space Complexity: O(1) because no additional space proportional to input size is used.
1def isPalindrome(x: int) -> bool:
2 if x < 0 or (x % 10 == 0 and x != 0):
3 return False
4 reversedHalf = 0
5 while x > reversedHalf:
6 reversedHalf = reversedHalf * 10 + x % 10
7 x //= 10
8 return x == reversedHalf or x == reversedHalf // 10
9
The function handles special cases for negative numbers and those ending in zero. It reverses the second half of the number and compares it with the first half, using integer operations for efficiency.