Problems related with numbers are frequently solved by / and %. No need of extra space is required. This problem is similar with the Reverse Integer problem.
Modding (%) the input int by 10 will extract off the rightmost digit. example: (1234 % 10) = 4
Multiplying an integer by 10 will “push it left” exposing a zero to the right of that number, example: (5 X 10) = 50
Dividing an integer by 10 will remove the rightmost digit. (75 / 10) = 7
Note: no extra space here means do not convert the integer to string, since string will be a copy of the integer and take extra space. The space take by div, left, and right can be ignored.
publicbooleanisPalindrome(int x) {
//negative numbers are not palindromeif (x<0) {
returnfalse;
}
// initialize how many zerosint div = 1;
while (x / div >= 10) {
div *= 10;
}
while (x != 0) {
int left = x / div;
int right = x % 10;
if (left != right) {
returnfalse;
}
x = (x % div) / 10;
div /= 100;
}
returntrue;
}