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.
1#include <iostream>
2
3bool isPalindrome(int x) {
4 if (x < 0) return false;
5 std::string str = std::to_string(x);
6 int n = str.size();
7 for (int i = 0; i < n / 2; ++i) {
8 if (str[i] != str[n - i - 1]) return false;
9 }
10 return true;
11}
12
We check if the number is negative, returning false early if it is. We convert the integer to a string and compare each character from the start and end moving toward the center. If all pairs match, the integer is a palindrome.
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.
1function isPalindrome(x) {
2 if (x < 0 || (x % 10 === 0 && x !== 0)) return false;
3 let reversedHalf = 0;
4 while (x > reversedHalf) {
5 reversedHalf = reversedHalf * 10 + x % 10;
6 x = Math.floor(x / 10);
7 }
8 return x === reversedHalf || x === Math.floor(reversedHalf / 10);
9}
10
Negative checks are performed initially. The function uses a loop to construct a reversed number from the digits of the original by comparison. This approach avoids the need for strings and utilizes arithmetic directly on the digits.