9. Palindrome Number

来源:互联网 发布:会java学python 编辑:程序博客网 时间:2024/06/05 05:53

题目描述:

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.

https://leetcode.com/problems/palindrome-number/description/


思路分析:判断一个数是不是回文数(palindrome),并对使用的空间有所要求,所以采用的是直接反转数字,而没有使用字符串解决。

应注意,负数不是回文数,因为符号没法反转到最后一位,为防止越界,使用long来存储回文。


代码:

class Solution {public:    bool isPalindrome(int x) {    if (x<0){            return false;        }                int a = x;        long palindrome = 0;            while(x != 0){    palindrome = palindrome*10 + x%10;            x = x/10;    }                if (palindrome == a)            return true;        else            return false;    }};


时间复杂度:O(logn)

反思:基础不牢导致有很多小细节考虑不到。!=是一个连起来的符号,不能分开的;对于条件的判断也没考虑清楚,忘记来else,导致没有返回值的情况出现。

原创粉丝点击