Wednesday, July 9, 2014

[Leetcode] Palindrome Number

Problem

Determine whether an integer is a palindrome. Do this without extra space.

Algorithm

O(n^2) Solution
Using a pick(int x, int d) method, which can pick the dth digit of x, we can determine if an integer is a palindrome. This pick method can be realized 

int pick(int x, int d){
     while(d > 1){
          x /= 10;
          d--;
     }
     return x%10;
}
Since, picking each digit needs O(n) time, the total running time is O(n^2). 

O(n) Solution
Note, changing line 9 to while(x>9), cannot pass the test case x = 1021.
Note, instead of using a loop, recursively call isPalindrome method after line 15 also cannot pass the test case  x = 1021.

Why does this code work? For example, x = 1021
x = 1021, div = 1000, msd = 1, lsd = 1
x = 2, div = 10, msd = 0, lsd = 2

false

Code



No comments:

Post a Comment