LeetCode | 9. Palindrome Number(回文串)

来源:互联网 发布:湖南领导干部网络教育 编辑:程序博客网 时间:2024/06/05 11:15

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.

解题思路:注意负数不算回文串以及不允许使用额外空间(O(1)应该是允许的),再有就是处理溢出.

class Solution {public:    bool isPalindrome(int x)    {        long long tmp = 0;//it will not overflow        if(x < 0)        {            return false;        }        int t2 = x;        while(t2)        {            tmp = tmp*10 + (t2%10);            t2 /= 10;        }        if(tmp>INT_MAX)        {            return false;        }        return tmp==x;    }};
1 0
原创粉丝点击