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 bool IsPalindrome(int x) {
3 if (x < 0) return false;
4 string str = x.ToString();
5 int n = str.Length;
6 for (int i = 0; i < n / 2; i++) {
7 if (str[i] != str[n - i - 1]) return false;
8 }
9 return true;
10 }
11}
12
The method converts the integer to a string. It then iterates over the string, comparing characters from the start and the end, moving toward the center. If any characters mismatch, it returns false, otherwise true if all 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.
1#include <stdbool.h>
2
3bool isPalindrome(int x) {
4 if (x < 0 || (x % 10 == 0 && x != 0)) return false;
5 int reversedHalf = 0;
6 while (x > reversedHalf) {
7 reversedHalf = reversedHalf * 10 + x % 10;
8 x /= 10;
9 }
10 return x == reversedHalf || x == reversedHalf / 10;
11}
12
The function checks if the number is negative or ends with a zero (and is not zero itself), returning false in those cases. It then sequentially takes digits from the end of the number, constructing a reversed half. The loop terminates once reversedHalf equals or exceeds the original half of the number, allowing us to check equality.