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 Pointerto0and theRight Pointerto the last index - While
Left Pointeris 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
truebecause 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
RightPartto0andleftPartto yournumber - If
numberis negative ornumberfirst digit is0returnfalse. It can’t be a palindrome - While the
RightPartis inferior to theLeftPart:- Add the first digit of
LeftParttoRightPartbyRightPart = RightPart * 10 /to add a new number/ + LeftPart % 10 /change the new number by the first digit of LeftPart/ - Divide
LeftPartby 10 to lose one digit
- Add the first digit of
- return the comparison between
LeftPartandRightPartorLeftPartand (RightPartdivided 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;
}
};