Code: Select all

```
Input: 121
Output: true
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
```

The idea is to get the last digit of the input and make this the first digit of a temp variable that I will use to compare against. Doing this for half of the digits will yield the result. E.g:

Input: 1221

halved: 12 | 21

get the last digit with input % 10 -> 1

make it the first digit of temp: temp = temp * 10 + last digit.

integer divide input by 10 to get to the next digit.

Do this for half of the digits. But how do you know when you've reached half? Each iteration the input decreases x10 and the temp increases 10x so

when temp > input it's done. E.g:

Code: Select all

```
- Input: 12321 temp: 0
- Input: 1232 temp: 1
- Input: 123 temp: 12
- input: 12 temp:123
```

Code: Select all

```
public boolean isPalindrome(int x) {
if (x < 0) return false;
if (x % 10 == 0 && x != 0) return false;
int temp = 0;
while(temp < x) {
int r = x % 10;
temp = temp * 10 + r;
x = x/10;
}
// even number of digits e.g 1221
if (x == temp) return true;
// odd number of digits e.g 121. temp will be 12 and x will 1, so temp/10 get rid
// of last digit.
if (temp/10 == x) return true;
return false;
}
```