首页 > 其他 > 详细

Palindrome Number ---- LeetCode 009

时间:2016-03-31 14:23:27      阅读:185      评论:0      收藏:0      [点我收藏+]

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

Some hints:

Could negative integers be palindromes? (ie, -1)

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: (with extra space)

技术分享
 1 class Solution
 2 {
 3 public:
 4     bool isPalindrome(int x)
 5     {
 6         if(x == 0) return true;
 7         if(x < 0) return false;
 8         
 9         vector<int> v;
10         bool flag = true;
11 
12         // 若x = 13314, 则v为4 1 3 3 1
13         while(x != 0)
14         {
15             v.push_back(x % 10);
16             x = x / 10;
17         }
18         
19         auto left = v.begin(), right = prev(v.end());
20         for(; left < right; ++left, --right)  //  注意: left < right
21         {
22             if(*left != *right)
23             {
24                 flag = false;
25                 break;
26             }
27         }
28         return flag;
29     }
30 };
View Code

Solution 2:

技术分享
class Solution
{
public:
    bool isPalindrome(int x)
    {
        if(x < 0) return false;
        else if(x == 0) return true;
        
        bool flag = true;
        
        int temp = x, y = 0;
        while(x != 0)
        {
            y = y * 10 + x % 10;
            x = x / 10;
        }
        if(y != temp) flag = false;
        return flag;
    }
};
View Code

 

Palindrome Number ---- LeetCode 009

原文:http://www.cnblogs.com/xuyan505/p/5340710.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!