Problem:
Determine whether an integer is a palindrome. Do this without extra space.
Analysis:
One tricky way to do this is to convert it into string and then use the normal palindrome way to solve the problem. Though it violates the requirement of "no extra space", the online judger won't judge whether we are using extra space or not.
The normal way is to check from the leftmost and rightmost digit, toward the mid digit. Give special attention to negative numbers
Code:
Tricky way:
View Code
Normal way:
View Code
1 public class Solution { 2 public boolean isPalindrome(int x) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 if (x < 0) return false; 6 7 int base = 1; 8 while (x / base >= 10) { 9 base *= 10; 10 } 11 12 13 int left=0, right=0; 14 while (x > 0) { 15 left = x / base; 16 right = x % 10; 17 18 if (left != right) 19 return false; 20 21 22 x = (x - left*base) / 10; 23 base /= 100; 24 } 25 26 return true; 27 } 28 }
Attention: