Problem Statement:
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.
-
Return
falsefor negative numbers (not Palindromes).
Constraints:
Time Complexity: O(d)Where dis the number of
digits.
Space Complexity: Only a few variables are used.
O(1)
Examples:
Input:121
Output:true
Input:-121
Output:false
Input:10
Output:false
Approach:
-
Handle Negatives:If
x < 0, return false. -
Store OriginalSave the input
in
xCopyfor comparison. -
Reverse:Intialize
rev = 0whilex > 0 : rem = x % 10 rev = rev * 10 + rem x //= 10 -
Compare:If
rev === xCopyreturntrue;elsefalse.
Flow Chart:
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
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
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
}
}
#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 <limits.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;
}
using System;
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int number = int.Parse(Console.ReadLine());
if (IsPalindrome(number))
Console.WriteLine("The number is a palindrome.");
else
Console.WriteLine("The number is not a palindrome.");
}
static bool IsPalindrome(int number)
{
int original = number;
int reversed = 0;
while (number > 0)
{
int digit = number % 10;
reversed = reversed * 10 + digit;
number /= 10;
}
return original == reversed;
}
}
