Monday, June 29, 2015

808: Reverse Integer / Integer Palindrome

The popularity of my Find the middle of linked list in one pass post here is another classic interview question.  Once again the goal of this question is to see if you strip away the libraries and tools from the software engineer does she still have to fundamentals needed to think through a problem.

Determine if a given integer is a palindrome. 


(think about it before you jump to see what the answer is)

.              

..

...

....

..... 

....

...

..

.

Once you complete your solution on the whiteboard ask a question or two. Such as can negative numbers be consider palindromes? Can numbers that end in zero be palindromes? (example: does 100 == 00100) Asking a question shows your understanding of the problem and the ways algorithm can be enhanced.


Java Solution:



boolean isPalindrome(int x) {
 return x == reverse(x);
}

int reverse(int x) {
 int result = 0;
 int digit = x;
 
 while (digit > 0) {
  int modulus = digit % 10;
  digit = digit / 10;
  result = result * 10 + modulus;
 }
 return result;
}


Related Content:

No comments:

Post a Comment