Write a function isPalindrome(x) that takes an integer x and returns true if it reads the same backward and forward; otherwise false.
Requirements
- Handles both positive and negative integers.
- Returns
falsefor negative numbers (not palindromes).
Constraints
- Time Complexity:
O(d)wheredis the number of digits. - Space Complexity:
O(1)— Only a few variables are used.
Examples
Input: 121
Output: true
Input: -121
Output: false
Input: 10
Output: false
Step-by-Step Approach
- Handle Negatives: If
x < 0, returnfalse. - Store Original: Save the input in
xCopyfor comparison. - Reverse:
- Initialize
rev = 0. - While
x > 0:rem = x % 10rev = rev * 10 + remx //= 10
- Initialize
- Compare: If
rev === xCopy, returntrue; elsefalse.
var isPalindrome = function(x) {
if (x < 0) return false;
let xCopy = x;
let rev = 0;
while (x > 0) {
let rem = x % 10;
rev = rev * 10 + rem;
x = Math.floor(x / 10);
}
return rev === xCopy;
};
console.log(isPalindrome(121)); // true
#include <iostream>
using namespace std;
class Solution {
public:
bool isPalindrome(int x) {
if (x < 0) return false;
int xCopy = x;
long long rev = 0;
while (x > 0) {
int rem = x % 10;
rev = rev * 10 + rem;
x /= 10;
}
return rev == xCopy;
}
};
int main() {
Solution sol;
cout << boolalpha << sol.isPalindrome(121) << endl; // true
return 0;
}
#include <stdio.h>
#include <stdbool.h>
bool isPalindrome(int x) {
if (x < 0) return false;
int xCopy = x;
long long rev = 0;
while (x > 0) {
int rem = x % 10;
rev = rev * 10 + rem;
x /= 10;
}
return rev == xCopy;
}
int main() {
int num = 121;
printf("%s\n", isPalindrome(num) ? "true" : "false");
return 0;
}
public class Solution {
public boolean isPalindrome(int x) {
if (x < 0) return false;
int xCopy = x;
int rev = 0;
while (x > 0) {
int rem = x % 10;
rev = rev * 10 + rem;
x /= 10;
}
return rev == xCopy;
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println(sol.isPalindrome(121)); // true
}
}
class Solution:
def isPalindrome(self, x):
if x < 0:
return False
x_copy = x
rev = 0
while x > 0:
rem = x % 10
rev = rev * 10 + rem
x //= 10
return rev == x_copy
sol = Solution()
print(sol.isPalindrome(121)) # True
