9. Palindrome Number

My Solution (String Builder and compare)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public boolean isPalindrome(int x) {
// convert to string
String str = String.valueOf(x);
// new string builder
StringBuilder sb = new StringBuilder();
// save from tight to left
for (int pos = str.length() - 1; pos >= 0; pos--) {
sb.append(str.charAt(pos));
}
// compare strings
return str.equals(sb.toString());
}
}

Math

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public boolean isPalindrome(int x) {
// negative & end with `0`
if (x < 0 || (x % 10 == 0 && x != 0)) return false;

int reverted = 0;
while (x > reverted) {
reverted = reverted * 10 + x % 10;
x /= 10;
}

// caompare first half and last half
return x == reverted || x == reverted / 10;
}
}

Remarks:

  1. Use reverted/10 to ignore the middle number (if odd)