Palindrome Number
PROBLEM
Given an integer x
, return true
if x
is a palindrome, and false
otherwise.
Example1
*Input*: x = 121
*Output*: true
*Explanation*: 121 reads as 121 from left to right and from right to left.
Example2
*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.
Example3
*Input*: x = 10
*Output*: false
*Explanation*: Reads 01 from right to left. Therefore it is not a palindrome.
SOLVING
Two Pointers Method
Steps
- Transform the integer to string
- Add your
Left Pointer
to0
and theRight Pointer
to the last index - While
Left Pointer
is inferior to theRight Pointer
:- If Left Element is different from Right Element, return
false
. The string isn’t a palindrome
- If Left Element is different from Right Element, return
- Return
true
because we parse all the string and all character were the same
Code
class Solution {
public:
bool isPalindrome(int x) {
string nbStr = to_string(x);
int leftPtr = 0;
int rightPtr = nbStr.size() - 1;
while (leftPtr < rightPtr) {
if (nbStr[leftPtr] != nbStr[rightPtr])
return false;
leftPtr++;
rightPtr--;
}
return true;
}
};
Revert Half
Steps
- Initialize var
RightPart
to0
andleftPart
to yournumber
- If
number
is negative ornumber
first digit is0
returnfalse
. It can’t be a palindrome - While the
RightPart
is inferior to theLeftPart
:- Add the first digit of
LeftPart
toRightPart
byRightPart = RightPart * 10 /to add a new number/ + LeftPart % 10 /change the new number by the first digit of LeftPart/
- Divide
LeftPart
by 10 to lose one digit
- Add the first digit of
- return the comparison between
LeftPart
andRightPart
orLeftPart
and (RightPart
divided by10
)
Code
class Solution {
public:
bool isPalindrome(int x) {
int rightPart = 0;
int leftPart = x;
if (x < 0 || (x != 0 && x % 10 == 0))
return false;
while (rightPart < leftPart) {
rightPart = rightPart * 10 + leftPart % 10;
leftPart /= 10;
}
return leftPart == rightPart || leftPart == rightPart / 10;
}
};