码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:Palindrome Number

时间:2016-03-11 12:01:20      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:

9. Palindrome Number

 
Total Accepted: 111012 Total Submissions: 357341 Difficulty: Easy

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.

   

        求出整数长度,将整数的后一半翻转,再跟前一半比较,这样肯定比原整数的值小,不可能发生溢出。注意,当整数位数为奇数时中间位的处理,我的方法中将该位删除了。

class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0) return false;
        int len = IntLen(x);
        int tmp = 0;
        for (int i = 0; i < len / 2; i++)
        {
            tmp = tmp * 10 + x % 10;
            x = x / 10;
        }
        if (len % 2 == 1)   //若整数为奇数位,将中间一位删除
            x = x / 10;
        if (tmp == x)
            return true;
        else
            return false;
    }
    int IntLen(int x)
    {
        int i = 0;
        while (x)
        {
            i++;
            x = x / 10;
        }
        return i;
    }
};

 

LeetCode:Palindrome Number

标签:

原文地址:http://www.cnblogs.com/luchenxu/p/5264617.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!