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 <stdbool.h>
2#include <stdio.h>
3#include <string.h>
4
5bool isPalindrome(int x) {
6 if (x < 0) return false;
7 char str[12];
8 sprintf(str, "%d", x);
9 int len = strlen(str);
10 for (int i = 0; i < len / 2; i++) {
11 if (str[i] != str[len - i - 1]) return false;
12 }
13 return true;
14}
15
The function checks if the integer is negative, returning false immediately if so, as negative numbers can't be palindromes. We convert the integer into a string and use a loop to compare characters from the start and end of the string. If they match all the way to the middle, the number 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.
1class Solution {
2public:
3 bool 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};
13
The function first deals with negative numbers and numbers ending with zero. It then reverses digits from the end of the number to form half of the reversed number. This leverages integer arithmetic properties to compare the first half with the second half of the number.