Saturday, May 9, 2015

Palindrome Number

来源:Leetcode

原帖:http://oj.leetcode.com/problems/palindrome-number/

题目:
Determine whether an integer is a palindrome. Do this without extra space. Some hints: Could negative integers be palindromes? (ie, -1) (No!)
If you are thinking of converting the integer to string, note the restriction of using extra space.
You could also try reversing an integer. However, if you have solved the problem "Reverse Integer",
you know that the reversed integer might overflow. How would you handle such case?
There is a more generic way of solving this problem.
Solution:
1. Count the number of digits first (traverse once) then check the digits from both sides to center.
2. Reverse the number, then check to see if x == reverse(x).
3. Recursion (interesting but a little hard to understand).
Take 12321 as an example.
[1] x = 1, y = 12321;
[2] x = 12, y = 1232;
[3] x = 123, y = 123;
[4] x = 1232, y = 12;
[5] x = 12321, y = 1; done!

代码:
1] 对称寻找
 class Solution {  
 public:    
   bool isPalindrome(int x) {  
     if (x < 0) return false;  
     int d = 1;  
     while (x / d >= 10) d *= 10;  
     while (d > 1) {  
       if (x % 10 != x / d) return false;          
       x = x % d / 10;  
       d /= 100;  
     }  
     return true;  
   }  
 };  

2] Reverse integer
 class Solution {  
 public:  
   bool isPalindrome(int x) {  
     if (x < 0) return false;  
     return x == reverse(x);  
   }  
   
   int reverse(int x) {  
     int rev = 0;  
     while (x) {  
       rev = rev * 10 + x % 10; //! consider overflow here  
       x /= 10;  
     }  
     return rev;  
   }  
 };  

3] Recursion
 class Solution {  
 public:  
   bool isPalindrome(int x) {  
     return isPalindromeHelper(x, x);  
   }  
     
   bool isPalindromeHelper(int x, int &y) {  
     if (x < 0) return false;  
     if (x == 0) return true;  
     if (isPalindromeHelper(x / 10, y) && x % 10 == y % 10) {  
       y /= 10;  
       return true;  
     }  
     return false;  
   }  
 };  

No comments:

Post a Comment