[Leetcode] Palindrome Number

Palindrome Number 题解

题目来源:https://leetcode.com/problems/palindrome-number/description/


Description

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


class Solution {
public:
    bool isPalindrome(int x) {
        if (x < 0 || (x > 0 && x % 10 == 0))
            return false;
        int half = 0;
        while (x > half) {
            half *= 10;
            half += x % 10;
            x /= 10;
        }
        return (x == half || x == half / 10);
    }
};


解题描述

这道题题意是求一个给出的整数是不是一个回文数,并且不能使用额外的空间(空间复杂度为O(1))。题目的hint也指出了需要考虑的几种主要的情况:

  • 负数不是回文数,因为负号的存在
  • 溢出有可能要纳入考虑范围

上面给出的解法思想是,取出数字的在字符串上的后半串的反转half,与前半串即变换后的x进行对比来证明是否是回文数。

这里要注意到的一种特殊情况是数字位数为奇数,如输入为12321,则得到的half = 123,变换后的x = 12,所以要对half先除以10,因为中间那位不需要纳入比较范围。

posted @ 2018-01-29 09:45  言何午  阅读(99)  评论(0编辑  收藏  举报