
Problem Statement
In the problem at hand, we are tasked to determine whether a given integer x
is a palindrome. A palindrome in the context of integers is a number that remains the same when its digits are reversed. Understanding this concept is essential as it forms the foundation of our problem-solving approach. We need to translate this property of palindromes into a logical condition that can be applied programmatically for any integer within the specified range.
Examples
Example 1
Input:
x = 121
Output:
true
Explanation:
121 reads as 121 from left to right and from right to left.
Example 2
Input:
x = -121
Output:
false
Explanation:
From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3
Input:
x = 10
Output:
false
Explanation:
Reads 01 from right to left. Therefore it is not a palindrome.
Constraints
-231 <= x <= 231 - 1
Approach and Intuition
To solve whether a number is a palindrome, let's analyze the examples along with the constraints:
Intuition and Pseudocode
- If the number is negative, it cannot be a palindrome by definition because the negative sign would not be a part of the 'reversed' number's sequence.
- Similarly, any integer that ends in 0 but is not 0 itself cannot be a palindrome because its reversed form would not retain the leading zero.
Stemming from the above observations, we can derive the following plan:
- Check if the number is negative or ends in 0 but is not 0 itself. In these cases, directly return
false
. - Convert the integer into a string to easily reverse and compare.
- Compare the original string to its reversed counterpart.
- If they are identical, the number is a palindrome.
Using this plan, we can easily infer results for the given examples:
- Example 1:
121
is a palindrome because its reverse is121
itself. - Example 2:
-121
cannot be a palindrome because reversing it gives us121-
. - Example 3:
10
reverses to01
, thus not a palindrome.
This structured approach simplifies our understanding and implementation while adhering to the constraints of the problem.
Solutions
- C++
- Java
- C
- JavaScript
- Python
class Solution {
public:
bool checkPalindrome(int number) {
if (number < 0 || (number % 10 == 0 && number != 0)) {
return false;
}
int reversedNumber = 0;
while (number > reversedNumber) {
reversedNumber = reversedNumber * 10 + number % 10;
number /= 10;
}
return number == reversedNumber || number == reversedNumber / 10;
}
};
The provided C++ program defines a method to check whether a given integer is a palindrome. A palindrome number reads the same backwards as forwards.
- Initial validation ensures negative numbers and non-zero numbers that end with zero aren't falsely identified as palindromes.
- The function uses a reverse operation where the last digit of the number is repeatedly extracted and used to form a new reversed number. The original number is simultaneously reduced by removing its last digit.
- This process continues until the reversed number is equal to or greater than the reduced original number.
- The function finally checks if the entire original number or the truncated half matches the reversed number, accounting for both even and odd length numbers.
Ensure understanding of integer division and modulo operations when analyzing the reversal mechanism in the function. This ensures the method correctly handles edge cases such as numbers ending in zero.
public class Solution {
public boolean checkPalindrome(int number) {
if (number < 0 || (number % 10 == 0 && number != 0)) {
return false;
}
int reverseNumber = 0;
while (number > reverseNumber) {
reverseNumber = reverseNumber * 10 + (number % 10);
number /= 10;
}
return number == reverseNumber || number == reverseNumber / 10;
}
}
Determine whether an integer is a palindrome in Java by reversing half of the number and comparing it with the other half. Here is how to perform the check:
- Rule out negative numbers and multiplies of 10 (except 0) immediately, as they cannot be palindromes.
- Initialize
reverseNumber
to zero to build the second half of the integer. - Loop until you've processed half of the digits:
- Extract the last digit of
number
and append it toreverseNumber
. - Reduce
number
by removing the last digit.
- Extract the last digit of
- After finishing the loop, compare
number
withreverseNumber
for equality. If the input number has an odd number of digits, usereverseNumber / 10
for the comparison to drop the middle digit.
The algorithm determines if a number reads the same backward as forward by considering both the whole and the half-reversed number. This provides a simpler and more memory-efficient solution compared to reversing the entire number.
bool checkPalindrome(int number) {
if (number < 0 || (number % 10 == 0 && number != 0)) {
return false;
}
int reversedHalf = 0;
while (number > reversedHalf) {
reversedHalf = reversedHalf * 10 + number % 10;
number /= 10;
}
return number == reversedHalf || number == reversedHalf / 10;
}
The provided C code implements a function checkPalindrome
to determine whether a given integer is a palindrome. Palindromes are numbers that read the same backward as forward. Specifically, this function works as follows:
- Initially, the function checks if the input number is negative or if it ends with a zero (but is not zero itself); if either condition is true, the function returns
false
because such numbers cannot be palindromes. - It initializes a variable
reversedHalf
to store the digits of the reversed lower half of the number. - The function then enters a loop that continues until the original number is greater than the calculated
reversedHalf
. Inside the loop, it peels off the last digit of the number and appends it toreversedHalf
, simultaneously reducing the original number by a factor of 10 (removing the last digit). - At the exit of the loop, the function checks if the original number is either equal to
reversedHalf
or equal toreversedHalf
divided by 10 (to account for numbers with an odd number of digits).
If these conditions are satisfied, the function returns true
, indicating the number is a palindrome; otherwise, it returns false
. This method efficiently checks for palindromes by only reversing up to half of the number and comparing with the remaining half, making it memory and time efficient.
var checkPalindrome = function(number) {
if (number < 0 || (number % 10 == 0 && number != 0)) {
return false;
}
let reverse = 0;
while (number > reverse) {
reverse = reverse * 10 + (number % 10);
number = Math.floor(number / 10);
}
return number == reverse || number == Math.floor(reverse / 10);
};
The function checkPalindrome
determines whether a given integer is a palindrome. A number is considered a palindrome if it reads the same backward as forward.
- Begin by checking if the number is negative or ends in zero (excluding zero itself); if either condition is true, the function immediately returns false.
- Initialize a variable
reverse
to zero. This variable builds the reversed version of the number incrementally. - Use a while loop to generate the reversed number. This loop continues as long as the original number is greater than the reversed number.
- Within the loop, append the last digit of
number
toreverse
by multiplyingreverse
by 10 and adding the last digit ofnumber
. - Reduce
number
by removing its last digit. - After exiting the loop, compare the original halved number (
number
) with the reversed number or with the reversed number truncated by its last digit to handle both odd and even length numbers. - Returns true if they are equal, confirming the number is a palindrome; otherwise, returns false.
class Solution:
def checkPalindrome(self, num: int) -> bool:
if num < 0 or (num % 10 == 0 and num != 0):
return False
reversed_num = 0
while num > reversed_num:
reversed_num = reversed_num * 10 + num % 10
num //= 10
return num == reversed_num or num == reversed_num // 10
This Python solution addresses the problem of determining if a given integer is a palindrome, meaning it reads the same forwards and backwards. The method works by reversing half of the number, comparing it to the other half to ascertain if the initial number is symmetrical.
- First, check if the number is negative or ends with a zero but is not zero itself. If either condition is met, the number is not a palindrome.
- Then, initialize a variable to store the reversed number.
- Using a loop, extract the last digit of the number and append it to the reversed number, updating the original number by removing its last digit.
- Continue the process until the reversed number is greater than or equal to what's left of the original number.
- Finally, compare the reversed number or its integer division by ten (to handle odd digit numbers) with the original truncated number to verify if both halves match.
This method efficiently checks for palindromicity without converting the number to a string, leveraging integer operations for a space-efficient solution.
No comments yet.